function fieldHoverShow(){
    $('#dlg-config').on('mouseover','.datagrid-header td:not([title])[field]',function(){
        var key = $(this).attr('field');
        if(key && key !== "buttonArr" && key !== "__blank"){
             $(this).attr('title',key);
        }
    });
    $('#entity-attr').on('mouseover','label.form-lable:not([title])',function(){
        var inputObj =$(this).next('.input-block').children().eq(0);
        var key = inputObj.attr('id');
        if(key){
             $(this).attr('title',key);
        }
    });
}
function loadGridForTemplateDtl(el,dictType){
     var opts = {
        readonly: JsonReadonly,
        url: zGlobal["http"] + "/api/autocode/templateDtl/list?limit=100&page=1",
        queryParams:{templateId: dictType,"sort":"orderNum","order":"desc"},
        idField: 'templateFileId',
        textField: 'fileTitle',
        columns: [[
            {field: 'templateFileId', title: '模板文件ID', align: 'center', width: 300 },
            {field: 'fileTitle', title: '文件标题', align: 'center', width: 240 },
            {field: 'outputFileFormat', title: '输出格式', align: 'center', width: 80 },
            {field: 'quoteTag', title: '模板引用名', align: 'center', width: 100 },
            {field: 'outputType', title: '模板类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"template.outputType")} },
        ]]
    };
    zUtil.inputInit(el,"cgrid",opts);
}

function dlgConfigReplace(type){
    if(JsonReadonly){
        zUtil.msg('只读模式不能修改');
        return false;
    }
    
    zUtil.formClear('#dlg-config-replace');
    zUtil.val($('#dlg-config-replace #replaceType'),"1");
    zUtil.val($('#dlg-config-replace #wholeWord'),"1");
    
    var dlgClose = function(){
      zUtil.dialogClose('#dlg-config-replace');
    };
    var dlgOptions = {
      title: '替换配置内容关键字',
      width: 500,
      height: 250,
      collapsible: true,
      modal: false,
      buttons:[{
          text:'替换',
          handler: function(){
              if(!zUtil.formCheck('#dlg-config-replace')){
                    return false;
              };
              var configContentStr = zUtil.val($('#dlg-edit-right #configContent'));
                  var replaceType = zUtil.val($('#dlg-config-replace #replaceType'));
                  var wholeWord = zUtil.val($('#dlg-config-replace #wholeWord'));
                  var oldstr = zUtil.val($('#dlg-config-replace #oldstr'));
                  var newstr = zUtil.val($('#dlg-config-replace #newstr'));
                  if(newstr === "NAN"){
                       newstr = '';
                  }
                  
                  var matchStr = [];
                  if(configContentStr&&configContentStr.length>0){
                      try{
                          if(replaceType === "2"){
                          }else{
                             oldstr= oldstr.replace(new RegExp("\\^|\\$|\\*|\\+|\\-|\\.|\\?|\"|\'|\\\\|\\[|\\]|\\(|\\)|\\{|\\}|\\|",'g'),function(c) {
                                return "\\"+c;
                             });
                             if(wholeWord === '1'){
                                 oldstr =  '\\b' + oldstr + '\\b';
                             }
                          }
                          matchStr = configContentStr.match(new RegExp(oldstr,'g'));
                          configContentStr = configContentStr.replace(new RegExp(oldstr,'g'),newstr);
                          zUtil.val($('#dlg-edit-right #configContent'), configContentStr);
                          if(matchStr && matchStr.length>0){
                              matchStr =  '共替换 '+matchStr.length+' 处';
                          }else{
                              matchStr =  '共替换 0 处';
                          }
                          zUtil.Toastr("success","替换成功."+matchStr,null,{positionClass:"toast-top-center"});
                      }catch(b){
                          zUtil.Toastr("error","替换失败",null,{positionClass:"toast-top-center"});
                          return false;
                      }
                  }else{
                      zUtil.Toastr("warn","不需要替换",null,{positionClass:"toast-top-center"});
                  }
                }
         }
      ]
    };
    var dlgButtonsIdx = [1];
    var dlgButtonsFunc = [dlgClose];
    zUtil.dialogInit2('#dlg-config-replace',dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen('#dlg-config-replace');
}
function dlgConfigJsonView(type){

}


function dlgJeditor(type){
    var jsonOpts = JeditorAttrDefine();
    
    if(type === "LA1" || type === "LE1"){
        jsonOpts.schema.required = ["attrExtendModule","attrExtendField"];
    }
    
    if(JsonJeditor !== null){
        zUtil.jeditorClear(JsonJeditor);
    }
    
    if(type === "LA1"){
        IdDlgRightOpen = IdDlgAddLeft;
    }else if(type === "LE1"){
        IdDlgRightOpen = IdDlgEditLeft;
    }else if(type === "RA1"){
        IdDlgRightOpen = IdDlgAddRight;
    }else if(type === "RE1"){
        IdDlgRightOpen = IdDlgEditRight;
    }
    
    var configVal = {};
    var functionKeyVal = zUtil.parse(zUtil.val(IdDlgRightOpen + " #functionKey"));
    var attrExtendModuleVal = zUtil.parse(zUtil.val(IdDlgRightOpen + " #attrExtendModule"));
    var attrExtendFieldVal = zUtil.parse(zUtil.val(IdDlgRightOpen + " #attrExtendField"));
    var tableInterfaceVal = zUtil.parse(zUtil.val(IdDlgRightOpen + " #tableInterface"));
    
    if(functionKeyVal!=null){
      configVal["functionKey"] = functionKeyVal;
    }
    if(attrExtendModuleVal!=null){
      configVal["attrExtendModule"] = attrExtendModuleVal;
    }
    if(attrExtendFieldVal!=null){
      configVal["attrExtendField"] = attrExtendFieldVal;
    }
    if(tableInterfaceVal!=null){
        configVal["tableInterface"] = tableInterfaceVal;
    }
    JsonJeditor = zUtil.jeditor(IdDlgJeditor + " #jsonedit_JSON",jsonOpts,configVal);
    
    var dlgSave = function(){
        const data = zUtil.jeditorData(JsonJeditor);
        if(data != null){
          var functionKeyDt = data["functionKey"];
          var attrExtendModuleDt = data["attrExtendModule"];
          var attrExtendFieldDt = data["attrExtendField"];
          var tableInterfaceDt = data["tableInterface"];
          
          var checkKeyFunc = function(key,title, keymaps){
              if(!key || !title){
                  zUtil.msg("属性编码/标题不能为空 ");
                  return false;
              }
              if(keymaps[key]){
                  zUtil.msg("属性编码已被使用 " + key);
                  return false;
              }else{
                  var usedKeys =["buttonArr","_uniqueId","_leftId","state","entityData","children"
                      ,"outputModulePath","moduleKeyName","moduleKey","loadTemplate","loadDict","parentModuleKey"
                      ,"loadDictFunc"
                      ,"methodKeyName","methodKey","methodUrl","methodCode1" ,"methodCode2","methodCode3"
                      ,"complexTableFlag","methodOprType","needFlag","selectTemplate"
                      ,"conditionSymbol","useModuleCode","useMethodCode"
                      ,"fieldTitle","fieldCode","fieldJavaCode","fieldJavaCode2","fieldUseType"
                      ,"fieldType","standardFlag","javaFullType","javaType","javaVoType","jdbcType"
                      ,"inputType","inputNumber","gridClonums","inputVal","inputDict","componentType"
                      ,"inputClass","pageShowFlag","groupName","groupCode","pageOrder","readonlyFlag"
                      ,"inputOptions1","inputOptions2","useTableCode","useTableSqlCode"
                      ,"mustFlag","checkBackground","checkPage","checkType","maxVal","minVal"];
                  
                  var flag = false;
                  $.each(usedKeys,function(i,item){
                      console.log(key +"----"+ item);
                      if(key.toLowerCase() === item.toLowerCase()){
                          zUtil.msg("属性编码已被使用 " + item);
                          flag = true;
                          return false;
                      }
                  });
                  if(flag){
                      return false;
                  }
              }
              keymaps[key] = "Y";
              return true;
          };
          var errflag = true;
          
          if(functionKeyDt && functionKeyDt["attrFunc"]){
              var attrFuncDt = functionKeyDt["attrFunc"]
              var hasmethodCodes = {};
              $.each(attrFuncDt,function(i,item){
                  var title = item['title'];
                  var key = item['key'];
                  if(!key || !title){
                      zUtil.msg("方法编码/标题不能为空 ");
                      errflag = false;
                      return false;
                  }
                  else if(hasmethodCodes[key.toLowerCase()]){
                      zUtil.msg("方法编码不能相同 " + key);
                      errflag = false;
                      return false;
                  }
                  hasmethodCodes[key.toLowerCase()] = "Y";
              });
          }
          if(tableInterfaceDt){
              var hasCodes = {};
              $.each(tableInterfaceDt,function(i,item){
                  var title = item['title'];
                  var key = item['key'];
                  if(!key || !title){
                      zUtil.msg("数据库接口编码/标题不能为空 ");
                      errflag = false;
                      return false;
                  }
                  else if(hasCodes[key.toLowerCase()]){
                      zUtil.msg("数据库接口编码不能相同 " + key);
                      errflag = false;
                      return false;
                  }
                  hasCodes[key.toLowerCase()] = "Y";
              });
          }
          
          if(errflag && functionKeyDt && functionKeyDt["attrExtendFunc"]){
              var attrExtendFuncDt = functionKeyDt["attrExtendFunc"];
              var keymaps = {};
              $.each(attrExtendFuncDt,function(i,item){
                  var key = item['code'];
                  var title = item['title'];
                  errflag = checkKeyFunc(key,title,keymaps);
                  return errflag;
              });
          }
          if(errflag && attrExtendModuleDt){
              var keymaps = {};
              $.each(attrExtendModuleDt,function(i,item){
                  var key = item['code'];
                  var title = item['title'];
                  errflag = checkKeyFunc(key,title,keymaps);
                  return errflag;
              });
          }
          if(errflag && attrExtendFieldDt){
              var keymaps = {};
              $.each(attrExtendFieldDt,function(i,item){
                  var key = item['code'];
                  var title = item['title'];
                  errflag = checkKeyFunc(key,title,keymaps);
                  return errflag;
              });
          }
          if(!errflag){
              return;  
          }
          zUtil.val(IdDlgRightOpen + " #functionKey", zUtil.strify(functionKeyDt));
          zUtil.val(IdDlgRightOpen + " #attrExtendModule", zUtil.strify(attrExtendModuleDt));
          zUtil.val(IdDlgRightOpen + " #attrExtendField", zUtil.strify(attrExtendFieldDt));
          zUtil.val(IdDlgRightOpen + " #tableInterface", zUtil.strify(tableInterfaceDt));
          
        }
        zUtil.jeditorClear(JsonJeditor);
        zUtil.dialogClose(IdDlgJeditor);
    };
    var dlgClose = function(){
      zUtil.jeditorClear(JsonJeditor);
      zUtil.dialogClose(IdDlgJeditor);
    };
    var dlgOptions = {
      title: 'JSON编辑',
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    if(JsonReadonly){
        dlgButtonsIdx = [1];
        dlgButtonsFunc = [dlgClose];
    }
    zUtil.dialogInit(IdDlgJeditor,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);   
    zUtil.dialogOpen(IdDlgJeditor);
}
function JeditorAttrDefine() {
    const attrExJson = {
        "type": "object",
        "title": "属性",
        "required": ["code", "title", "type", "loadtype", "option"],
        "properties": {
            "code": {
                "type": "string",
                "title": "唯一编码(code)",
                "default": "z_",
                "minLength": 4,
                "readOnly": JsonReadonly,
                "options": {
                    "input_width": '150px'
                }
            },
            "title": {
                "type": "string",
                "title": "标题(title)",
                "default": "字段_",
                "minLength": 2,
                "readOnly": JsonReadonly,
                "options": {
                    "input_width": '150px'
                }
            },
            "type": {
                "type": "string",
                "title": "输入类型(type)",
                "enum": ["1", "2", "3", "4", "5"],
                "default": "1",
                "readOnly": JsonReadonly,
                "options": {
                    "enum_titles": ["布尔", "文本", "单选", "多选", "文本域"],
                    "input_width": '90px'
                },
            },
            "loadtype": {
                "type": "string",
                "title": "输入来源(loadtype)",
                //"format": "select2",
                "enum": ["blank", "data", "url"],
                "default": "blank",
                "readOnly": JsonReadonly,
                "options": {
                    "enum_titles": ["无", "静态数据", "URL"],
                    "input_width": '100px'
                },
                "watch": {
                    "types": "type",
                },
            },
            "mores": {
                "type": "object",
                "title": "配置(mores)",
                "format": "grid",
                "required": ["text", "value", "method"],
                "options": {
                    "disable_properties": true,
                    "disable_edit_json": true,
                    "input_width": '360px',
                    "collapsed": true,
                },
                "properties": {
                    "text": {
                        "type": "string",
                        "title": "标签(text)",
                        "default": "text",
                        "readOnly": JsonReadonly,
                        "options": {
                            "grid_columns": 4
                        }
                    },
                    "value": {
                        "type": "string",
                        "title": "值(value)",
                        "default": "value",
                        "readOnly": JsonReadonly,
                        "options": {
                            "grid_columns": 3
                        }
                    },
                    "method": {
                        "type": "string",
                        "title": "请求方式(method)",
                        "default": "get",
                        "readOnly": JsonReadonly,
                        "enum": ["get", "post"],
                        "options": {
                            "grid_columns": 5,
                            "enum_titles": ["GET", "POST"],
                        }
                    },
                    "data": {
                        "type": "string",
                        "description": "",
                        "title": "数据(data)",
                        "format": "textarea",
                        "readOnly": JsonReadonly,
                        "options": {
                            "input_height": '60px',
                            "grid_columns": 12
                        }
                    },
                }

            },
        }
    };
    var jsonOpts = {
        "schema": {
            "type": "object",
            "title": "基础属性定义",
            "required": ["functionKey", "attrExtendModule", "attrExtendField", "tableInterface"],
            "options": {
                "disable_collapse": true,
                "disable_properties": true,
            },
            "properties": {
                "functionKey": {
                    "type": "object",
                    "title": "模块方法扩展",
                    "format": "table",
                    "required": ["attrFunc", "attrExtendFunc"],
                    "options": {
                        "disable_edit_json": true,
                        "disable_properties": true,
                        "collapsed": true,
                    },
                    "properties": {
                        "attrFunc": {
                            "type": "array",
                            "title": "方法定义",
                            "uniqueItems": true,
//                            "minItems": 1,
                            "format": "table",
                            "options": {
                                "collapsed": true,
                            },
                            "items": {
                                "type": "object",
                                "title": "方法",
                                "format": "table",
                                "required": ["code", "title", "attrExtendFunc"],
                                "properties": {
                                    "title": {
                                        "type": "string",
                                        "title": "标题(title)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '100px',
                                        }
                                    },
                                    "key": {
                                        "type": "string",
                                        "title": "唯一编码(key)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '150px',
                                        }
                                    },
                                    "url": {
                                        "type": "string",
                                        "title": "链接(url)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '230px',
                                        }
                                    },
                                    "code1": {
                                        "type": "string",
                                        "title": "预留编码(code1)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '150px',
                                        }
                                    },
                                    "code2": {
                                        "type": "string",
                                        "title": "预留编码(code2)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '150px',
                                        }
                                    },
                                    "code3": {
                                        "type": "string",
                                        "title": "预留编码(code3)",
                                        "minLength": 2,
                                        "readOnly": JsonReadonly,
                                        "options": {
                                            "input_width": '150px',
                                        }
                                    },
                                }
                            }
                        },
                        "attrExtendFunc": {
                            "type": "array",
                            "title": "方法属性扩展",
                            "uniqueItems": true,
                            "format": "table",
                            "options": {
                                "collapsed": true,
                                "grid_columns": 12,
                            },
                            "items": attrExJson
                        }
                    }
                }
                ,"tableInterface": {
                    "type": "array",
                    "title": "表方法扩展",
                    "uniqueItems": true,
                    "format": "table",
                    "options": {
                        "collapsed": true,
                    },
                    "items": {
                        "type": "object",
                        "title": "方法",
                        "format": "table",
                        "required": ["key", "title"],
                        "properties": {
                            "title": {
                                "type": "string",
                                "title": "标题(title)",
                                "minLength": 2,
                                "readOnly": JsonReadonly,
                                "options": {
                                    "input_width": '200px',
                                }
                            },
                            "key": {
                                "type": "string",
                                "title": "唯一编码(key)",
                                "minLength": 2,
                                "readOnly": JsonReadonly,
                                "options": {
                                    "input_width": '150px',
                                }
                            },
                            "code": {
                                "type": "string",
                                "title": "命名编码(code)",
                                "minLength": 2,
                                "readOnly": JsonReadonly,
                                "options": {
                                    "input_width": '300px',
                                }
                            },
                        }
                    }
                }
                ,"attrExtendModule": {
                    "type": "array",
                    "title": "模块属性扩展",
                    "uniqueItems": true,
                    "format": "table",
                    "options": {
                        "collapsed": true,
                    },
                    "items": attrExJson
                }
                ,"attrExtendField": {
                    "type": "array",
                    "title": "对象属性扩展",
                    "uniqueItems": true,
                    "format": "table",
                    "options": {
                        "collapsed": true,
                    },
                    "items": attrExJson
                },
                
                
            }
        },
        "theme": "bootstrap3",
        "disable_array_add": JsonReadonly,
        "disable_array_delete": JsonReadonly,
        "disable_array_reorder": JsonReadonly,
    };
    return jsonOpts;
}
  
//TODO
function dlgConfig(type){
  zUtil.formClear(IdDlgConfig);
  if(JsonReadonly){
    zUtil.readonlyAll("#table-config-template-show1");
    $('.template-show').hide();
  }else{
    zUtil.readonlyAll("#table-config-template-show1",false);
    $('.template-show').show();
  }
  IdTableConfigEdit = null;//编辑对象
  IdTableConfigEditIdx = null;//编辑索引
  ObjParamConfig1 =[];
  ObjParamConfig2 =[];
  ObjParamConfig3 =[];
  MethodEntityCopyIdx = null;
  MethodEntityEditIndex = null;
  SelectTemplateMethod = [];
  SelectTemplateTable = [];
  ConfigFirstFlag = true;
  
  var leftRowData = getTableLeft();
  
  var jsonFieldId = null;
  if(type === "RA1"){//新增
      IdDlgRightOpen =  IdDlgAddRight;
  }else if(type === "RE1"){//编辑
      IdDlgRightOpen =  IdDlgEditRight;
  }
  jsonFieldId = IdDlgRightOpen + " #configContent";
  
  var attrExtendModuleJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #attrExtendModule"));
  var attrFunctionKeyJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #functionKey"));
  var tableInterfaceJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #tableInterface"));
  var configContentJSON = zUtil.parse(zUtil.val(jsonFieldId));
  
  if(configContentJSON == null || JSON.stringify(configContentJSON) === '{}'){
      configContentJSON = {"mainJSON":{}, "methodJSON":null, "templateJSON":null,"tableJSON":null};
  }
  if(attrFunctionKeyJSON == null){
      attrFunctionKeyJSON = {};
  }
  if(attrExtendModuleJSON == null){
      attrExtendModuleJSON = [];
  }
  if(tableInterfaceJSON == null){
      tableInterfaceJSON = [];
  }
  if(zUtil.val(IdDlgRightOpen +" #moduleKeyName") == null 
      || zUtil.val(IdDlgRightOpen +" #moduleKey") == null){
      zUtil.msg("先填写模块名称/编码");
      return;
  };
  
  var resultTemplate = zUtil.ajaxGetSync(zGlobal["http"] + "/api/autocode/templateDtl/list", {templateId: leftRowData['templateId'],"limit":100,"page":1});
  var templateRows = resultTemplate[zConst["resData"]][zConst["data"]];//获取模板信息
  if(!templateRows || templateRows.length === 0){
      zUtil.msg("未获取到模板记录");
      return;
  }
  
  var hasMaps ={};
  var tsameFlag = false;
  $.each(templateRows,function(i,item){
      if(hasMaps[item['quoteTag']]){
          zUtil.msg("模板编码不能相同");
          tsameFlag = true;
          return false;
      }
      if(!item['quoteTag']){//为空直接跳过
          return true;
      }
      if(item['quoteTag'].toLowerCase() === "own"){
          zUtil.msg("不能使用own作为模板编码");
          tsameFlag = true;
          return false;
      }
      hasMaps[item['quoteTag']] = "Y";
  });
  if(tsameFlag){
      return;
  }
  
  templateRows = templateRows.sort(function(a,b){
      var result = parseInt(a['outputType'])-parseInt(b['outputType']);
      return result === 0? parseInt(a['orderNum'])-parseInt(b['orderNum']):result;
  });
  
  var dlgSave = function(){
      var allconfig = {};
      var params = zUtil.tableData(IdTableConfigMain)["rows"];
      var params2 = zUtil.tableData(IdTableConfigMethod)["rows"];
      var params3 = zUtil.tableData(IdTableConfigTemplate)["rows"];
      var params4 = zUtil.treegrid(IdTableConfigTbl,'getdt');
      var checkOwnkeys = function(key,rules){
          var flag = false;
          $.each(rules,function(i,item){
              if(key.toLowerCase() === item.toLowerCase()){
                  flag = true; 
                  return false;
              }
          });
          return flag
      };
      if(params != null && params.length>0){
          var cdata ={};
          var cfieldEx ={};
          var ownkeys = ["moduleKeyName","moduleKey","outputModulePath","loadTemplate","loadDict"
               ,"loadDictFunc","parentModuleKey"];
          for(var i=0; i<params.length;i++){
              const key = params[i]['field'];
              const value = params[i]['value'];
              if(checkOwnkeys(key,ownkeys)){
                 cdata[key] = value;
              }else{
                 cfieldEx[key] = value; 
              }
          }
          
          cdata['fieldEx'] = cfieldEx;
          allconfig['mainJSON'] = cdata;
          
          zUtil.val(IdDlgRightOpen +" #moduleKeyName", cdata['moduleKeyName']);
          zUtil.val(IdDlgRightOpen +" #moduleKey", cdata['moduleKey']);
          zUtil.val(IdDlgRightOpen +" #outputModulePath", cdata['outputModulePath']);
      }
      if(params2 != null && params2.length>0){
          var ownkeys = ["buttonArr","_uniqueId","methodKey","methodKeyName","methodUrl","methodCode1"
              ,"methodCode2","methodCode3","entityData","selectTemplate","needFlag","complexTableFlag","methodOprType"];
          var entitykeys = ["buttonArr","_uniqueId","fieldTitle","fieldCode","fieldJavaCode","fieldJavaCode2","selectTemplate"
              ,"fieldUseType","fieldType","standardFlag","javaFullType","javaType","javaVoType","jdbcType"
              ,"inputType","inputNumber","gridClonums","inputVal","inputDict","componentType"
              ,"inputClass","pageShowFlag","groupName","groupCode","pageOrder","readonlyFlag"
              ,"inputOptions1","inputOptions2","inputOptions3","useTableCode","useTableSqlCode","conditionSymbol","useModuleCode","useMethodCode"
              ,"mustFlag","checkBackground","checkPage","checkType","maxVal","minVal","children"
              ];
          
          var doHandleData = function(data){
              if(data && data.length>0){
                  $.each(data,function(i,item){
                      //不要
                      delete item['_parentId'];
                      delete item['checkState'];
                      delete item['checked'];
                      delete item['state'];
                      delete item['_leftId'];
                      
                      doHandleData(item['children']);
                  });
              }
          };
          var doHandleData2 = function(data){
              if(data && data.length>0){
                  $.each(data,function(i,item){
                      var entitydata = {};
                      var entityfieldEx ={};
                      $.each(item,function(fkey,fval){
                          if(checkOwnkeys(fkey,entitykeys)){
                              if(fkey === 'children'){
                                  doHandleData2(fval);  
                              }
                              entitydata[fkey] = fval;
                          }else{
                              entityfieldEx[fkey] = fval;
                          }
                      });
                      entitydata['fieldEx'] = entityfieldEx;
                      data[i] = entitydata;
                  });
              }
          };
          
          var hasMaps ={};
          var cdataFunc =[];
          var cdataMethod =[];
          for(var i=0; i<params2.length;i++){
              var carr = $.extend(true,{},params2[i]);
              var methodKey = carr['methodKey'];
              if(hasMaps[methodKey] || allconfig['mainJSON']['moduleKey'] == methodKey){
                zUtil.msg("方法编码不能相同");
                return;
              }
              hasMaps[carr['methodKey'].toLowerCase()] = "Y";
              cdataFunc.push({
                  "key": carr['methodKey'],
                  "title": carr['methodKeyName'],
                  "url": carr['methodUrl'],
                  "code1": carr['methodCode1'],
                  "code2": carr['methodCode2'],
                  "code3": carr['methodCode3'],
              });
              
              var cdata = {};
              var cfieldEx ={};
              $.each(carr,function(key,value){
                  if(checkOwnkeys(key,ownkeys)){
                     if("entityData" === key && value){
                         $.each(value,function(ekey,eval){
                            doHandleData(eval);
                            doHandleData2(eval);
                         });
                         cdata[key] = value;
                     }else{
                         cdata[key] = value;
                     }
                  }else{
                     cfieldEx[key] = value; 
                  }
              });
              cdata['fieldEx'] = cfieldEx;
              cdataMethod.push(cdata);
          }
          
          attrFunctionKeyJSON['attrFunc'] = cdataFunc;
          
          allconfig['methodJSON'] = cdataMethod;
          
          zUtil.val(IdDlgRightOpen +" #functionKey", zUtil.strify(attrFunctionKeyJSON));
      }
      if(params3 != null && params3.length>0){
          var hasMaps ={};
          for(var i=0; i<params3.length;i++){
              if(hasMaps[params3[i]['quoteTag']]){
                  zUtil.msg("模板编码不能相同");
                  return;
              }
              hasMaps[params3[i]['quoteTag']] = "Y";
          }
          allconfig['templateJSON'] = params3;
      }
      if(params4 != null && params4.length>0){
          var doHandleData = function(data){
               if(data['children']){
                  delete data['children'];
               }
               delete data['_parentId'];
               delete data['checkState'];
               delete data['checked'];
               delete data['state'];
               delete data['_leftId'];
          };
          var tbldatas =  $.extend(true,[],params4);
          $.each(tbldatas,function(i,item){
              var childrenVal = item['children'];
              var sqlInterfaces = [];
              if(childrenVal && childrenVal.length > 0){
                  $.each(childrenVal,function(sqli,sqlitem){
                     sqlInterfaces.push({
                          "sqlTitle": sqlitem['tableTitle'],
                          "sqlCode": sqlitem['tableCode'],
                          "sqlId": sqlitem['tableJavaCode'],
                          "sqlDesc": sqlitem['tableDesc'],
                          "needFlag": sqlitem['needFlag'],
                          "tableData": sqlitem['tableData'],
                          "entityData": sqlitem['entityData'],
                          "whereData": sqlitem['whereData'],
                          "sqlType": sqlitem['sqlType'],
                          "sqlGenerateType": sqlitem['sqlGenerateType'],
                          "parameterType": sqlitem['parameterType'],
                          "returnType": sqlitem['returnType'],
                          "parameterTypeXml": sqlitem['parameterTypeXml'],
                          "returnTypeXml": sqlitem['returnTypeXml'],
                          "customField": sqlitem['customField'],
                          "customField2": sqlitem['customField2'],
                          "customField3": sqlitem['customField3'],
                          "customField4": sqlitem['customField4'],
                      });
                      doHandleData(sqlitem);
                  });
              }
              item['sqlInterfaces'] = sqlInterfaces;
              doHandleData(item);
          });
          allconfig['tableJSON'] = tbldatas;
      }
      
      zUtil.val(jsonFieldId, zUtil.strify(allconfig));
      if(ConfigCloseFlag){
          zUtil.dialogClose(IdDlgConfig);
      }
  };
  var dlgClose = function(){
      zUtil.dialogClose(IdDlgConfig);
  };
  var dlgOptions = {
    title: '属性编辑',
    cls: 'text-left',
    onBeforeClose:function(){
       zUtil.dialogClose(IdDlgUsePath);
       zUtil.dialogClose(IdDlgMethodEntityEdit);
       
       tableEditForReject();
       configForMethodEntityEditReject();
       configForTableEditReject();
    },
    buttons:  [{
        text:'保存不关闭',
        id:'z-dialog-notclosesave',
        iconCls:'fa fa-floppy-o',
        handler: function(){
            ConfigCloseFlag = false;
            dlgSave();
            ConfigCloseFlag = true;
        }
    }]
  };
  var dlgButtonsIdx = [0,1];
  var dlgButtonsFunc = [dlgSave,dlgClose];
  if(JsonReadonly){
      dlgButtonsIdx = [1];
      dlgButtonsFunc = [dlgClose];
      dlgOptions['buttons'] = [];
  }
  var ddss = zUtil.dialogInit(IdDlgConfig,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);   
  zUtil.dialogOpen(IdDlgConfig);
  
  //加载模块/方法树形菜单
  var ctabs = zUtil.elInit(IdTableConfigTabs,"tab",{
      onSelect: function(title,index){
          tableEditForReject();
          configForMethodEntityEditReject();
          configForTableEditReject();
          
          configForMethodEntity(templateRows,title,index);
          if(index === 2){
            //模板
            configForTemplate(templateRows,configContentJSON);
          }
          if(index === 1){
              configForTableCodeEditor1();
          }
      }
  });
  
  if(ConfigTabSelectIdx){
      $(IdTableConfigTabs).tabs("select",ConfigTabSelectIdx);
  }else{
      $(IdTableConfigTabs).tabs("select",0);
  }
  
  //模块
  configForMain(configContentJSON,attrExtendModuleJSON);
  //方法
  configForMethod(templateRows,configContentJSON,attrFunctionKeyJSON);
  //数据库表
  configForTable(templateRows,configContentJSON,tableInterfaceJSON);
  //模板
  configForTemplate(templateRows,configContentJSON);
}
function configForMain(configContentJSON,attrExtendModuleJSON){
        var mainJSON = configContentJSON['mainJSON'];
        var ppData = [
            {name: '模块编码',value:zUtil.val(IdDlgRightOpen + " #moduleKey"),field: 'moduleKey',group:'基本属性', editor: {type:'validatebox',options:{required:true}} },
            {name: '模块名称',value:zUtil.val(IdDlgRightOpen + " #moduleKeyName"),field: 'moduleKeyName',group:'基本属性', editor: {type:'validatebox',options:{required:true}} },
            {name: '模块路径',value:zUtil.val(IdDlgRightOpen + " #outputModulePath"),field: 'outputModulePath',group:'基本属性', editor: {type:'validatebox',options:{required:true}} },
            {name: '父级编码',value: mainJSON['parentModuleKey']?mainJSON['parentModuleKey']:null,field: 'parentModuleKey',group:'基本属性', editor: {type:'text',options:{}} },
            {name: '生成文件',value: mainJSON['loadTemplate']?mainJSON['loadTemplate']:'1',field: 'loadTemplate',group:'基本属性', editor: {type:'switchbox', options:{required:true,value:"1"}}  },
            {name: '加载字典',value: mainJSON['loadDict']?mainJSON['loadDict']:null,field: 'loadDict',group:'基本属性', editor: {type:'textarea',options:{}} },
            {name: '字典方法',value: mainJSON['loadDictFunc']?mainJSON['loadDictFunc']:null,field: 'loadDictFunc',group:'基本属性', editor: {type:'text',options:{}} },
        ];
        
        ObjParamConfig1.push({title:"模块编码",code:"moduleKey"});
        ObjParamConfig1.push({title:"模块名称",code:"moduleKeyName"});
        ObjParamConfig1.push({title:"模块路径",code:"outputModulePath"});
        ObjParamConfig1.push({title:"父级编码",code:"parentModuleKey"});
        
        var typeDATA = {};
        typeDATA['loadTemplate'] = getSwitchData();
        if(attrExtendModuleJSON != null){
            for(var i=0;i<attrExtendModuleJSON.length;i++){
                var col = createInputEl(attrExtendModuleJSON[i],"2");
                var cdata = zUtil.getVal(col,"editor.options.data");
                if(cdata!=null){
                    typeDATA[col['field']] = cdata;
                }
                ppData.push(col);
                
                ObjParamConfig1.push({title:col['title'],code:col['field']});
            }
            if(JsonReadonly){
              for(var i=0;i<ppData.length;i++){
                if(ppData[i].editor){
                  ppData[i].editor.type = ""; 
                }
              }
            }
        }
        var ppGetDataDesc = function(data,value){
            if(data != null){
                var dataobj ={};
                for(var i=0;i<data.length; i++){
                  dataobj[data[i]["value"]] = data[i]["text"];
                }
                var desc =[];
                if(value){
                    var vals = value.toString().split(",");
                    for(var j=0;j<vals.length;j++){
                      if(dataobj[vals[j]]){
                        desc.push(dataobj[vals[j]]);
                      }
                    }
                    if(desc.length>0){
                      return desc.join(",");
                    }
                }
            }
            if(value == null){
              value = "";
            }
            return value;
        };
        var ppCols = [{field:'name',title:'属性名',width:'120px',sortable:true,resizable:true},
                 {field:'value',title:'属性值',width:'170px',
                    formatter: function(value,rowData,rowIndex){ 
                      return ppGetDataDesc(typeDATA[rowData['field']],value);} }
              ,{field:'_blank',title:' ',width:'20px'}
           ];
        
        if(mainJSON != null){
            for(var i=0;i<ppData.length;i++){
                var field = ppData[i]['field'];
                var oVal = zUtil.getVal(mainJSON,"fieldEx."+field);
                if(field != null && oVal != null
                      && (field != "moduleKeyName" && field != "moduleKey" && field != "outputModulePath"
                         && field != "loadDict" && field != "loadDictFunc" && field != "parentModuleKey")){
                    ppData[i]['value'] = oVal;
                }
            }
        }
        var ppOptionsConfig = {
            data : ppData,
            columns: [ppCols],
            onAfterEdit: function(rowIndex, rowData, changes){
            }
        };
      
      zUtil.ppGridInit(IdTableConfigMain,ppOptionsConfig);
  }
function configForMethod(templateRows,configContentJSON,attrFunctionKeyJSON){
    var methodJSON = configContentJSON['methodJSON'];
      var methodMap = {};
      if(methodJSON != null){
          $.each(methodJSON,function(i,item){
              methodMap[item['methodKey']] = item;
          });
      }
      
      var excludeTemplateIdsVal = zUtil.val(IdDlgRightOpen + " #excludeTemplateIds");
      
      //模板处理
      var methodTemplates = [];
      var selectTemplates = [];
      var allTemplatesTags = {};
      $.each(templateRows,function(i,item){
          var flag = excludeTemplateIdsVal == null || (excludeTemplateIdsVal != null && excludeTemplateIdsVal.indexOf(item['templateFileId'])<0);
          var outputType = item['outputType'];
          var methodflag = (outputType === "3"||outputType === "2"||outputType === "7");
          if(methodflag && flag){
              var tt = {
                      "id": item['quoteTag'],
                      "text": item['quoteTag'],
                      "group": outputType,
                  };
              selectTemplates.push(item['quoteTag']);
              allTemplatesTags[item['quoteTag']] = "Y";
              methodTemplates.push(tt);
          }
      });
      SelectTemplateMethod = selectTemplates;
      
      var funcConfigData = {rows:[]};
      var attrFuncJSON = zUtil.getVal(attrFunctionKeyJSON,"attrFunc");
      if(attrFuncJSON != null){
          var doHandleData = function(data){
              if(data && data.length>0){
                  $.each(data,function(ei,eitem){
                      if(eitem['fieldEx']){
                          $.extend(true,eitem,eitem['fieldEx']);
                          delete eitem['fieldEx'];
                      }
                      doHandleData(eitem['children']);
                  });
              }
          };
          
          $.each(attrFuncJSON,function(i,item){
           var methodKey = item['key'];
           var tvo = {
                   "_uniqueId": zUtil.uuid(),
                   "methodKey":item['key'],
                   "methodKeyName": item['title'],
                   "methodUrl": item['url'],
                   "methodCode1": item['code1'],
                   "methodCode2": item['code2'],
                   "methodCode3": item['code3'],
                   "needFlag": item['needFlag']?item['needFlag']:"1",
                   "selectTemplate": item['selectTemplate']?item['selectTemplate']:selectTemplates.toString(),
                   "entityData": {},
           };
           var cmap = methodMap[methodKey];
           if(cmap){
               tvo['methodOprType'] = cmap['methodOprType'];
               tvo['complexTableFlag'] = cmap['complexTableFlag'];
               if(cmap['needFlag']){
                   tvo['needFlag'] = cmap['needFlag'];
               }
               if(cmap['selectTemplate']){
                   var selectTemplateDt = cmap['selectTemplate'].split(",");
                   var hasdt =[];
                   $.each(selectTemplateDt,function(i,item){
                       if(allTemplatesTags[item]){
                           hasdt.push(item);
                       }
                   });
                   tvo['selectTemplate'] = hasdt.toString();
               }
               if(cmap['entityData']){
                   var entityJSONDt = cmap['entityData'];
                   var hasdt ={};
                   $.each(entityJSONDt,function(key,item){
                       if(allTemplatesTags[key]){
                          var entityvo = $.extend(true,[],item);
                          doHandleData(entityvo);
                          hasdt[key]= entityvo;
                       }
                   })
                   tvo['entityData'] = $.extend(true,{}, hasdt);
               }
           }
           funcConfigData['rows'].push(tvo);
         });
      }
      var attrExtendFuncJSON = zUtil.getVal(attrFunctionKeyJSON,"attrExtendFunc");
      var funcTblcols = [
          {field: 'needFlag', title: '是否需要', align: 'center', width: 80,rowspan: 2, editor: {type:'switchbox', options:{required:true,value:"1"}}
             ,formatter: function(value,rowData,rowIndex){ return getSelectDataDesc(getSwitchData(),value); } 
             ,styler: function(value,row,index){
                 if (value === '0'){return 'color:red;';}
             }
          },
          {field: 'selectTemplate', title: '加载模板', align: 'center', width: 150,rowspan: 2, editor: {type:'combobox', 
              options:{valueField:'id',textField:'text',multiple:true,groupField: "group",panelHeight:200,data:methodTemplates,
                 groupFormatter: function(group){
                        return zUtil.dictConvertOfAutocode(group,"template.outputType");
                    }  }}
          },
          {field: 'methodOprType', title: '方法类型', align: 'center', width: 100, rowspan: 2
              , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.methodOprType'],0), panelHeight: 280 }}
              , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.methodOprType")} },
          {field: 'complexTableFlag', title: '多表操作', align: 'center', width: 80,rowspan: 2, editor: {type:'switchbox', options:{required:true,value:"1"}}
              ,formatter: function(value,rowData,rowIndex){ return getSelectDataDesc(getSwitchData(),value); } 
              ,styler: function(value,row,index){
                  if (value === '0'){return 'color:blue;';}
              }
           },
          {field: 'methodUrl', title: 'url链接', align: 'center', width: 130,rowspan: 2, editor: {type:'text'} },
          {field: 'methodCode1', title: '预留编码1', align: 'center', width: 130,rowspan: 2, editor: {type:'text'} },
          {field: 'methodCode2', title: '预留编码2', align: 'center', width: 130,rowspan: 2, editor: {type:'text'} },
          {field: 'methodCode3', title: '预留编码3', align: 'center', width: 130,rowspan: 2, editor: {type:'text'} },
          {field: 'fieldEx', title: '扩展属性', align: 'center', colspan: attrExtendFuncJSON && attrExtendFuncJSON.length>0?attrExtendFuncJSON.length : 1},
          {field: '__blank', title: ' ', align: 'center',width: 150, rowspan: 2}
      ];
      var funcTblcolsFZ = [
            {field:'buttonArr', title:'操作', align:'center', width: 80,rowspan: 2, formatter: function(value,rowData,rowIndex){
              return '<a href="javascript:void(0);" class="easyui-linkbutton" onclick="configForMethodToEntityConfig(\''+rowIndex+'\');">对象配置</a>';
            } },
            {field: 'methodKey', title: '方法编码', align: 'center', width: 100,rowspan: 2 },
            {field: 'methodKeyName', title: '方法名称', align: 'center', width: 100,rowspan: 2, editor: {type:'validatebox',options:{required:true}} },
      ];
      
      ObjParamConfig2.push({title:"方法编码",code:"methodKey"});
      ObjParamConfig2.push({title:"方法名称",code:"methodKeyName"});
      ObjParamConfig2.push({title:"预留编码1",code:"methodCode1"});
      ObjParamConfig2.push({title:"预留编码2",code:"methodCode2"});
      ObjParamConfig2.push({title:"预留编码3",code:"methodCode3"});
      
      var funcTblcols2 = [];
      if(attrExtendFuncJSON && attrExtendFuncJSON.length>0){
          for(var i=0;i<attrExtendFuncJSON.length;i++){
              var col = createInputEl(attrExtendFuncJSON[i],"1");
              funcTblcols2.push(col);
              
              var ztype = attrExtendFuncJSON[i].type;
              
              ObjParamConfig2.push({title:col.title,code:col.field});
              
              for(var j=0;j<funcConfigData['rows'].length;j++){
                  var mdata = funcConfigData['rows'][j];
                  var oVal = zUtil.getVal(methodMap, mdata['methodKey']+".fieldEx."+col.field);
                  if(methodMap && oVal != null){
                    mdata[col.field] = oVal;
                  }else{
                      if(ztype == "1" || ztype == "3" || ztype == "4"){
                          var cdata = zUtil.getVal(col,"editor.options.data");
                          if(cdata !== null && !mdata[col.field]){
                             mdata[col.field] = cdata[0].value;
                          }else{
                            mdata[col.field] = null;
                          }
                      }else{
                         mdata[col.field] = null;
                      }
                  }
              }
          }
      }else{
          funcTblcols2.push({field: '__blank', title: ' ', width: 100});
      }
      
      
      var buttonsIdxMethod = [0,6,7];
      var buttonsFuncMethod = [tableEditForAddOfMethod,tableEditForAccept,tableEditForReject];
      if(JsonReadonly){
        buttonsIdxMethod = null;
        buttonsFuncMethod = null;
      }
      var optionsMethod = {
              idField: '_uniqueId',
              data : funcConfigData,
              columns:[funcTblcols,funcTblcols2],
              frozenColumns:[funcTblcolsFZ,[]],
              onClickCell: function(rowIndex, field, value){
                tableEditForStart(field,rowIndex, IdTableConfigMethod);
              },
              onAfterEdit: function(rowIndex, rowData, changes){
                  configForTemplate(templateRows,configContentJSON);
              }
    };
    zUtil.tableInit2(IdTableConfigMethod,optionsMethod,buttonsIdxMethod,buttonsFuncMethod);
}
/* 跳转到方法对象配置*/
function configForMethodToEntityConfig(rowIndex){
    zUtil.tableSelected(IdTableConfigMethod,rowIndex);
    setTimeout(function(){
       $(IdTableConfigTabs).tabs("select",3);
    },100);
}

function configForTemplate(templateRows,configContentJSON){
    var templateData = {rows:[]};
    var templateJSON = configContentJSON["templateJSON"];
    var templateTblcols = [
//          {field: 'fileTitle', title: '文件标题', align: 'center', width: 120 },
//          {field: 'fromQuoteTag', title: '模板编码', align: 'center', width: 130 },
          {field: 'outputFileFormat', title: '输出格式', align: 'center', width: 80 },
          {field: 'loadTemplate', title: '生成文件', align: 'center', width: 80, editor: {type:'switchbox', options:{required:true, value:"1" }}
               ,formatter: function(value,rowData,rowIndex){ return getSelectDataDesc(getSwitchData(),value); }
               ,styler: function(value,row,index){
                   if (value === '0'){return 'background-color:#ffee00;color:red;';}
               }
          },
          {field: 'outputBasePath', title: '输出基础路径', align: 'left',halign: 'center', width: 130, editor: {type:'validatebox',options:{required:true}} },
          {field: 'outputPath', title: '输出路径', align: 'left',halign: 'center', width: 130, editor: {type:'validatebox',options:{}} },
          {field: 'outputFileName', title: '输出文件名', align: 'left',halign: 'center', width: 150, editor: {type:'validatebox',options:{required:true}} },
          {field: 'importClazz', title: 'import类路径', align: 'left',halign: 'center', width: 100, editor: {type:'textarea'} },
          {field: 'autowiredClazz', title: 'resource类名', align: 'left',halign: 'center', width: 100, editor: {type:'textarea'} },
          {field: 'extendClazz', title: 'extends类名', align: 'left',halign: 'center', width: 100, editor: {type:'text'} },
//          {field: 'importFile', title: '引入文件路径', align: 'center', width: 100, editor: {type:'text'} },
          
          {field: ' ', title: ' ', width: 100},
    ];
    var templateTblcolsFZ = [
          {field:'checkbox',title:'',align:'center',width: 60,checkbox:true},
          {field: 'quoteTag', title: '引用编码', align: 'left',halign: 'center', width: 180
              ,formatter: function(value,rowData,rowIndex){
                  var str1 = '<span style="color:#3852dd;">'+value.replace(rowData['fromQuoteTag'],'<span style="color:red;">'+rowData['fromQuoteTag']+'</span>')+'</span>';
                  return str1; }
          },
          {field: 'outputType', title: '模板类型', align: 'center', width: 90, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"template.outputType"); } },
    ];
    
    var tmap = {};
    if(templateJSON != null){//有配置信息
        $.each(templateJSON,function(i,item){
            if(!item['loadTemplate'] || item['loadTemplate'] === null){
                item['loadTemplate'] = "1";
            }
            var moduleFlag = item['outputType'] === "1";
            var methodFlag = item['outputType'] === "2" || item['outputType'] === "3";
            var tableFlag = item['outputType'] === "4" || item['outputType'] === "5";
            var childFlag = item['outputType'] === "6";
            /*if(!item['outputPath']){
                item['outputPath'] = "{A_outputModulePath}";
            }
            if(!item['outputFileName']){
                if(methodFlag){
                    item['outputFileName'] = "{UA_moduleKey}{UB_methodKey}";
                }else if(childFlag){
                    item['outputFileName'] = "{UB_methodKey}{UD_fieldJavaCode}";
                }else if(tableFlag){
                    item['outputFileName'] = "{UC_tableJavaFullCode}";
                }else{
                    item['outputFileName'] = "{UA_moduleKey}";
                }
            }*/
            tmap[item['quoteTag']] = item;
        });
    }
    
    var methodDatas = zUtil.tableData(IdTableConfigMethod)["rows"];
    var tableDatas = zUtil.treegrid(IdTableConfigTbl,'getdt');
    var childrenDtos = [];
    if(methodDatas && methodDatas.length>0){
        var childrenDtosKeys = {};
        var getChildrenDTOFunc = function(data,methodKey,needFlag,dtoKey){
            if(data && data.length>0){
                 $.each(data, function(idx, item){
                     if(item['fieldType'] === '2' || item['fieldType'] === '3'){
                         var haskey = dtoKey+methodKey+item['fieldJavaCode'];
                         if(!childrenDtosKeys[haskey]){
                             childrenDtosKeys[haskey] = true;
                             childrenDtos.push({
                                 "methodKey": methodKey,
                                 "dtoKey": dtoKey,
                                 "fieldJavaCode": item['fieldJavaCode'],
                                 "selectTemplate": item['selectTemplate'],
                                 "needFlag": needFlag,
                                 "loadTemplate": '1',
                            });
                            getChildrenDTOFunc(item['children'],methodKey,needFlag,dtoKey);
                        }
                     }
                 });
             }
         };
        
        $.each(methodDatas, function(i, mdx){
            var edto = mdx['entityData'];
            $.each(edto, function(dtoKey, dto){
                getChildrenDTOFunc(dto[0]['children'],mdx['methodKey'],mdx['needFlag'], dtoKey);
            });
        });
    }
    
    var excludeTemplateIdsVal = zUtil.val(IdDlgRightOpen + " #excludeTemplateIds");
    $.each(templateRows,function(key,val){
        var flag = excludeTemplateIdsVal == null || (excludeTemplateIdsVal != null && excludeTemplateIdsVal.indexOf(val['templateFileId'])<0);
        var moduleFlag = val['outputType'] === "1";
        var methodFlag = val['outputType'] === "2" || val['outputType'] === "3";
        var tableFlag = val['outputType'] === "4" || val['outputType'] === "5";
        var childFlag = val['outputType'] === "6";
        
        var quoteTag = val['quoteTag'];
        if((moduleFlag || methodFlag || tableFlag || childFlag) && flag){
            var tvo = {
                    "templateFileId": val['templateFileId'],
                    "projectId": val['projectId'],
                    "moduleId": val['moduleId'],
                    "templateId": val['templateId'],
                    "fileTitle": val['fileTitle'],
                    "fileName": val['fileName'],
                    "quoteTag": val['quoteTag'],
                    "fromQuoteTag": val['quoteTag'],
                    "outputFileFormat": val['outputFileFormat'],
                    "outputType": val['outputType'],
                    "loadTemplate":val['loadTemplate']?val['loadTemplate']:"1",
            };
            
           if(moduleFlag){
               var ntvo = $.extend(true,{},tvo);
               if(tmap[quoteTag]){
                  ntvo = $.extend(true,{},tmap[quoteTag],tvo);
               }
               templateData['rows'].push(ntvo);
           }else if(methodFlag){
               if(methodDatas && methodDatas.length > 0){
                   $.each(methodDatas,function(i,methodx){
                       var selectTemplateVal = methodx['selectTemplate'];
                       if(selectTemplateVal && selectTemplateVal !== null){
                           selectTemplateVal = selectTemplateVal.split(",");
                           $.each(selectTemplateVal,function(sti,stv){
                               if(stv === quoteTag){
                                   var ntvo = $.extend(true,{},tvo);
                                   var quoteTagx = quoteTag + "_"+ methodx['methodKey'];
                                   if(tmap[quoteTagx]){
                                       ntvo = $.extend(true,{},tmap[quoteTagx],tvo);
                                   }
                                   var newtvo = $.extend(true,{},ntvo);
                                   newtvo["quoteTag"] = quoteTagx;
                                   newtvo["fromKeyCode"] = methodx['methodKey'];
                                   if("0" === methodx['needFlag']){
                                       newtvo["loadTemplate"] = "0";
                                   }
                                   templateData['rows'].push(newtvo);
                               }
                           });
                       }
                   });
               }else{
                   var ntvo = $.extend(true,{},tvo);
                   if(tmap[quoteTag]){
                       ntvo = $.extend(true,{},tmap[quoteTag],tvo);
                   }
                   ntvo["loadTemplate"] = "0";//没有则不能生成
                   templateData['rows'].push(ntvo);
               }
           }else if(tableFlag){
               if(tableDatas && tableDatas.length > 0){
                   $.each(tableDatas,function(i,tblx){
                       var selectTemplateVal = tblx['selectTemplate'];
                       if(selectTemplateVal && selectTemplateVal !== null){
                           selectTemplateVal = selectTemplateVal.split(",");
                           $.each(selectTemplateVal,function(sti,stv){
                               if(stv === quoteTag){
                                   var ntvo = $.extend(true,{},tvo);
                                   var quoteTagx = quoteTag + "_"+ tblx['tableJavaCode'];
                                   if(tmap[quoteTagx]){
                                       ntvo = $.extend(true,{},tmap[quoteTagx],tvo);
                                   }
                                   var newtvo = $.extend(true,{},ntvo);
                                   newtvo["quoteTag"] = quoteTagx;
                                   newtvo["fromKeyCode"] = tblx['tableJavaCode'];
                                   if("0" === tblx['needFlag']){
                                       newtvo["loadTemplate"] = "0";
                                   }
                                   templateData['rows'].push(newtvo);
                               }
                           });
                       }
                   });
               }
               else{
                   var ntvo = $.extend(true,{},tvo);
                   if(tmap[quoteTag]){
                       ntvo = $.extend(true,{},tmap[quoteTag],tvo);
                   }
                   ntvo["loadTemplate"] = "0";//没有则不能生成
                   templateData['rows'].push(ntvo);
               }
           }
           else if(childFlag){
               if(childrenDtos && childrenDtos.length > 0){
                   $.each(childrenDtos,function(i,itemx){
                       var selectTemplateVal = itemx['selectTemplate'];
                       if(selectTemplateVal && selectTemplateVal !== null){
                           if(selectTemplateVal === quoteTag){
                               var ntvo = $.extend(true,{},tvo);
                               var quoteTagx = quoteTag + "_"+ itemx['methodKey']+ "_"+ itemx['fieldJavaCode'];
                               ntvo['loadTemplate'] = itemx['loadTemplate'];
                               if(tmap[quoteTagx]){
                                   ntvo = $.extend(true,{},tmap[quoteTagx],tvo);
                               }
                               var newtvo = $.extend(true,{},ntvo);
                               newtvo["quoteTag"] = quoteTagx;
                               newtvo["fromKeyCode"] = itemx['methodKey']+","+itemx['dtoKey']+","+itemx['fieldJavaCode'];
                               if("0" === itemx['needFlag']){
                                   newtvo["loadTemplate"] = "0";
                               }
                               templateData['rows'].push(newtvo);
                           }
                       }
                   });
               }else{
                     var ntvo = $.extend(true,{},tvo);
                     if(tmap[quoteTag]){
                         ntvo = $.extend(true,{},tmap[quoteTag],tvo);
                     }
                     ntvo["loadTemplate"] = "0";//没有则不能生成
                     templateData['rows'].push(ntvo);
              }
           }
        }
    });
    
    
      var buttonsIdxTemplate = [7,8];
      var buttonsFuncTemplate = [tableEditForReject,configForClearSelectTemplate];
      if(JsonReadonly){
        buttonsIdxTemplate = [];
        buttonsFuncTemplate = [];
      }
      
      var optionsTemplate = {
              data : templateData,
              columns: [templateTblcols],
              frozenColumns: [templateTblcolsFZ],
              idField:'quoteTag',
              singleSelect:false,
              toolbar:[
                  {
                      iconCls: 'fa fa-plus',
                      text:'选择已有模板配置',
                      handler: function(){
                          configForTemplateGetTemplateDlg();
                      }
                  }
              ],
              onClickCell: function(rowIndex, field, value){
                  tableEditForStart(field,rowIndex, IdTableConfigTemplate);
              },
              onClickRow: function(rowIndex, rowData){
                  zUtil.valAll(IdTableConfigTemplateShow,rowData);
              },
              onAfterEdit: function(rowIndex, rowData, changes){
                  zUtil.valAll(IdTableConfigTemplateShow,rowData);
              }
      };
      
      zUtil.tableInit2(IdTableConfigTemplate,optionsTemplate,buttonsIdxTemplate,buttonsFuncTemplate);
      zUtil.tableUnSelected(IdTableConfigTemplate);
      configContentJSON["templateJSON"] = zUtil.tableData(IdTableConfigTemplate)["rows"];
}
function configForClearSelectTemplate(){
    zUtil.tableUnSelected(IdTableConfigTemplate);
}
function configForTemplateGetTemplateDlg(){
    var dlgOptions = {
            title: '选择已有模板配置',
            width: 650,
            height: 500,
            toolbar: '#table-cfgtemplate-toolbar',
            onOpen:function(){
                 zUtil.tableInit('#table-cfgtemplate',{
                     queryParams:{},
                     url : zGlobal["http"] + "/api/autocode/cfgGenerateDtl/list",
                     idField: 'cfgGenerateDtlId',
                     sortName: 'orderNum',
                     sortOrder: 'desc',
                     multiSort: true,
                     columns:[[
                         {field: 'cfgGenerateDtlId', title: '生成配置明细主键ID', align: 'center', width: 100, hidden: true},
                         {field: 'cfgGenerateTitle', title: '配置标题', align: 'center', width: 120},
                         {field: 'projectId', title: '所属项目', align: 'center', width: 120, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT")}},
                         {field: 'moduleId', title: '所属模块', align: 'center', width: 120, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT_MODULE")}},
                         {field: ' ', title: ' ', align: 'center', width: 100},
                     ]],
                     frozenColumns:[[
                      {field: 'moduleKeyName', title: '模块名称', align: 'left',halign: 'center', width: 120},
                      {field: 'moduleKey', title: '模块编码', align: 'left',halign: 'center', width: 100},
                     ]],
             });
            }
    };
 var dlgButtonsIdx = [4,1];
 var dlgButtonsFunc =  [function(){
       var okfunc = function(){
           try{
               var sdata = zUtil.tableRows('#table-cfgtemplate');
               if(!sdata){
                   zUtil.msg('未选择记录');
                   return false;
               }
               /*var rrow = zUtil.tableRows(IdTableRight)[0];
               if(sdata['cfgGenerateDtlId'] === rrow['cfgGenerateDtlId']){
                   zUtil.msg('不能选择自身');
                   return false;
               }*/
               var detail = zUtil.ajaxGetSync(zGlobal["http"] + "/api/autocode/cfgGenerateDtl/detail", {"cfgGenerateDtlId":sdata['cfgGenerateDtlId']});
               if(zCode["GLOBAL_SUCCESS"] != zUtil.getVal(detail,zConst["busCode"])){
                 zUtil.msg('获取信息失败');
                 return false;
               }
               detail = detail["resData"];
               var configContent = zUtil.parse(detail['configContent']);
               var hasTemplateJSON = zUtil.getVal(configContent,'templateJSON');
               if(!hasTemplateJSON || hasTemplateJSON.length === 0){
                   zUtil.msg('未获取到模板配置');
                   return false;
               }
               var hasTagMap = {};
               $.each(hasTemplateJSON, function(i,item){
                   if(hasTagMap[item['fromQuoteTag']]){
                       return true;
                   }
                   hasTagMap[item['fromQuoteTag']] = item;
               });
               
               var templateall = zUtil.tableData(IdTableConfigTemplate)["rows"];
               $.each(templateall, function(i,item){
                   var t = hasTagMap[item['fromQuoteTag']];
                   if(t){
                       zUtil.table(IdTableConfigTemplate,'updrow',{index: i,row: {
                           "outputBasePath": t['outputBasePath'],
                           "outputPath":  t['outputPath'],
                           "outputFileName":  t['outputFileName'],
                           "importClazz":  t['importClazz'],
                           "autowiredClazz":  t['autowiredClazz'],
                           "extendClazz":  t['extendClazz']
                       }});
                   }
               });
               zUtil.dialogClose('#dlg-select-cfgtemplate');
           }catch(b){
              console.log(b);
           }
       };
       zUtil.msgConfirm('是否使用该模块的模板配置?',okfunc);
       
     },function(){
       zUtil.dialogClose('#dlg-select-cfgtemplate');
     }];
 zUtil.dialogInit('#dlg-select-cfgtemplate',dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
 zUtil.dialogOpen('#dlg-select-cfgtemplate');
}
function configForTemplateTableCfgtemplateRefresh(){
    var params = zUtil.valAll('#table-cfgtemplate-toolbar');
    zUtil.tableUnSelected('#table-cfgtemplate');
    zUtil.tableQuery('#table-cfgtemplate',params);
}
function configForTable(templateRows, configContentJSON, tableInterfaceJSON){
      var tableJSON = configContentJSON['tableJSON'];
      
      var excludeTemplateIdsVal = zUtil.val(IdDlgRightOpen + " #excludeTemplateIds");
      
      //模板处理
      var tableTemplates = [];
      var selectTemplates = [];
      var allTemplatesTags = {};
      $.each(templateRows,function(i,item){
          var flag = excludeTemplateIdsVal == null || (excludeTemplateIdsVal != null && excludeTemplateIdsVal.indexOf(item['templateFileId'])<0);
          var outputType = item['outputType'];
          var tableflag = (outputType === "4"||outputType === "5");
          if(tableflag && flag){
              var tt = {
                      "id": item['quoteTag'],
                      "text": item['quoteTag'],
                      "group": outputType,
                  };
              selectTemplates.push(item['quoteTag']);
              allTemplatesTags[item['quoteTag']] = "Y";
              tableTemplates.push(tt);
          }
      });
      SelectTemplateTable = selectTemplates;
      
      var dataTbl = [];
      if(tableJSON && tableJSON.length > 0){
          
          $.each(tableJSON,function(i,item){
              item["state"] = "closed";
              item["tableFlag"] = "1";
              item["iconCls"] = "fa fa-database";
              
              var sqlInterfaces = item["sqlInterfaces"];
               
              var children = [];
              
              if(tableInterfaceJSON && tableInterfaceJSON.length > 0){
                  var sqlmap = {};
                  if(sqlInterfaces && sqlInterfaces.length>0){
                      $.each(sqlInterfaces,function(sqli,sqlitem){
                          sqlmap[sqlitem['sqlCode']] = sqlitem;
                      });
                  }
                  
                  $.each(tableInterfaceJSON,function(i,item){
                      var _uniqueId = zUtil.uuid();
                      var node1 = {
                              "_uniqueId": _uniqueId,
                              "tableCode": item['key'],
                              "tableTitle": item['title'],
                              "tableJavaCode": item['code'],
                              "tableDesc": null,
                              "tableData": null,
                              "entityData": null,
                              "whereData": null,
                              "tableRels": null,
                              "needFlag": "1",
                              "tableFlag":"0",
                              "sqlType": null,
                              "sqlGenerateType":"1",
                              "iconCls":"fa fa-circle",
                              "parameterType": null,
                              "returnType": null,
                              "parameterTypeXml": null,
                              "returnTypeXml": null,
                      };                     
                      var hasdt = sqlmap[item['key']];
                      if(hasdt){
                          var node2 = $.extend(true,{},hasdt);
                          node1['tableDesc'] = node2['sqlDesc'];
                          node1['needFlag'] = node2['needFlag'];
                          node1['tableDesc'] = node2['sqlDesc'];
                          node1['tableData'] = node2['tableData'];
                          node1['entityData'] = node2['entityData'];
                          node1['whereData'] = node2['whereData'];
                          node1['sqlType'] = node2['sqlType'];
                          node1['sqlGenerateType'] = node2['sqlGenerateType'];
                          node1['customField'] = node2['customField'];
                          node1['customField2'] = node2['customField2'];
                          node1['customField3'] = node2['customField3'];
                          node1['customField4'] = node2['customField4'];
                          node1['parameterType'] = node2['parameterType'];
                          node1['returnType'] = node2['returnType'];
                          node1['parameterTypeXml'] = node2['parameterTypeXml'];
                          node1['returnTypeXml'] = node2['returnTypeXml'];
                      }
                      
                      children.push(node1);
                   });
              }
              
              item["children"] = children;
              delete item["sqlInterfaces"];
          });
          
          dataTbl = tableJSON;
      }
      
      var cols = [
          {field: 'needFlag', title: '是否需要', align: 'center', width: 80,rowspan: 2, editor: {type:'switchbox', options:{required:true,value:"1"}}
             ,formatter: function(value,rowData,rowIndex){ return getSelectDataDesc(getSwitchData(),value); } 
             ,styler: function(value,row,index){
                 if (value === '0'){return 'color:red;';}
             }
          },
          {field: 'selectTemplate', title: '加载模板', align: 'center', width: 150,rowspan: 2, editor: {type:'combobox', 
              options:{valueField:'id',textField:'text',multiple:true,groupField: "group",panelHeight:250,data:tableTemplates,
                 groupFormatter: function(group){
                        return zUtil.dictConvertOfAutocode(group,"template.outputType");
                 }  }}
          },
          {field: 'tableDesc', title: '描述', align: 'center', width: 100,rowspan: 2, editor: {type:'textarea'} },
          {field: 'tableJavaCode', title: '驼峰编码', align: 'center', width: 150,rowspan: 2 },
          {title: '表配置', align: 'center',colspan: 7 },
          {title: 'SQL配置', align: 'center',colspan: 6 },
          {field: 'customField', title: '预留字段', align: 'center', width: 100,rowspan: 2, editor: {type:'text'} },
          {field: 'customField2', title: '预留字段2', align: 'center', width: 100,rowspan: 2, editor: {type:'text'} },
          {field: 'customField3', title: '预留字段3', align: 'center', width: 100,rowspan: 2, editor: {type:'text'} },
          {field: 'customField4', title: '预留字段4', align: 'center', width: 100,rowspan: 2, editor: {type:'text'} },
          {field: '__blank', title: ' ', align: 'center',width: 150,rowspan: 2 }
      ];
      var cols2 = [
          {field: 'tableJavaFullCode', title: '驼峰编码(全)', align: 'center', width: 150, editor: {type:'text'} },
          {field: 'tableJavaCode2', title: '驼峰编码2', align: 'center', width: 150, editor: {type:'text'} },
          {field: 'tableAlias', title: '表别名', align: 'center', width: 100, editor: {type:'text'} },
          {field: 'tableType', title: '表模式', align: 'center', width: 120
              , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.tableType'],0), panelHeight: 100 }}
             , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.tableType")}},
          {field: 'tableKeyType', title: '主键类型', align: 'center', width: 120
              , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.tableKeyType'],0), panelHeight: 200 }}
             , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.tableKeyType")}},
          {field: 'tableKeyImpl', title: '主键实现', align: 'center', width: 100, editor: {type:'text'} },
          {field: 'tableRelReview', title: '审核联动表', align: 'center', width: 120, editor: {type:'text'} },
          {field: 'sqlGenerateType', title: 'SQL生成方式', align: 'center', width: 100
                 , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.sqlGenerateType'],0), panelHeight: 200 }}
                 , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.sqlGenerateType")} },
          {field: 'sqlType', title: 'SQL类型', align: 'center', width: 100
                 , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.tableSqlType'],0), panelHeight: 200 }}
                 , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.tableSqlType")} },
          {field: 'parameterType', title: '传入参数', align: 'center', width: 140, editor: {type:'text'} },
          {field: 'returnType', title: '返回参数', align: 'center', width: 140, editor: {type:'text'} },
          {field: 'parameterTypeXml', title: '传入参数Xml', align: 'center', width: 140, editor: {type:'text'} },
          {field: 'returnTypeXml', title: '返回参数Xml', align: 'center', width: 140, editor: {type:'text'} },
      ];
      var colsFZ = [
            {field:'buttonArr', title:'操作', align:'center', width: 80,hidden: JsonReadonly,rowspan: 2, formatter: function(value,rowData,rowIndex){
                var btns = [];
                if(rowData['tableFlag'] === "1"){
                    btns.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="configForTableDel(\''+rowData['_uniqueId']+'\');" >删除</a>');
                }
                return btns.join(" ");
              } },
            {field: 'tableCode', title: '表编码', align: 'left',halign:"center", width: 150,rowspan: 2 },
            {field: 'tableTitle', title: '标题', align: 'left', halign:"center", width: 100,rowspan: 2},
      ];
      
      ObjParamConfig3.push({title:"表编码",code:"tableCode"});
      ObjParamConfig3.push({title:"标题",code:"tableTitle"});
      ObjParamConfig3.push({title:"驼峰编码1",code:"tableJavaCode"});
      ObjParamConfig3.push({title:"驼峰编码(全)",code:"tableJavaFullCode"});
      ObjParamConfig3.push({title:"驼峰编码2",code:"tableJavaCode2"});
      
      if(JsonReadonly){
        buttonsIdxTbl = null;
        buttonsFuncTbl = null;
      }
      var optionsTbl = {
              data : dataTbl,
              columns:[cols,cols2],
              frozenColumns:[colsFZ,[]],
              idField: '_uniqueId',
              treeField:'tableCode',
              onClickCell: function(field, rowData){
                  configForTableEditStart(field, rowData);
              },
              onSelect: function(rowData){
                  configForTableEntity(rowData);
                  configForTableRel(rowData);
              },
              onClickRow: function(rowData){
                  if(rowData['tableFlag']!=="1"){
                      $('#dlg-config-t2').children().layout('collapse','west');
                  }
                 
                  var editObjs = zUtil.treegrid(IdTableConfigTbl,"getEditors",rowData['_uniqueId']);
                  $.each(editObjs, function(idx,item){
                      if(rowData['tableFlag'] === "0"){
                          if(item.field === "selectTemplate" || item.field === "tableJavaFullCode"
                              ||item.field === "tableJavaCode2" || item.field === "tableAlias"
                              || item.field === "tableKeyType"  || item.field === "tableKeyImpl"
                              || item.field === "tableRelReview" || item.field === "tableType"){
                              $(item.target).css("display","none")
                              $(item.target).next('span').css("display","none");
                          }
                      }else{
                          if(item.field === "sqlType" || item.field === "sqlGenerateType" 
                              || item.field === "parameterType" || item.field === "returnType"
                              || item.field === "parameterTypeXml" || item.field === "returnTypeXml"){
                              $(item.target).css("display","none")
                              $(item.target).next('span').css("display","none");
                          }
                      }
                      
                 });
              },
              onAfterEdit: function(rowData, changes){
                  configForTemplate(templateRows,configContentJSON);
              },
              toolbar:[
                  {   iconCls: 'fa fa-search',
                      text:'选择表',
                      handler: function(){
                           configForTableAddTable();
                           }
                   },{
                  iconCls: 'fa fa-refresh',
                  text:'同步表字段',
                  handler: function(){
                           configForTableRefreshTableCols();
                        }
                  },{
                      iconCls: 'fa fa-plus',
                      text:'添加SQL接口',
                      handler: function(){
                               configForTableAddSqlInterface();
                         }
                  }
             ]
      };
      zUtil.treegridInit2(IdTableConfigTbl,optionsTbl);
}
function configForTableAddSqlInterface(){
    var dlgOptions = {
               title: '新增Sql定义',
               width: 500,
               height: 190,
               onOpen:function(){
                   zUtil.formClear('#dlg-add-sqlinterface');
               }
       };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [function(){
          if(!zUtil.formCheck('#dlg-add-sqlinterface')){
              return false;
          }
          zUtil.dialogClose('#dlg-add-sqlinterface');
          ConfigTabSelectIdx = 1;
          var newdata = zUtil.valAll('#dlg-add-sqlinterface');
          var tableInterfaceJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #tableInterface"));
          if(!tableInterfaceJSON){
              tableInterfaceJSON = [];
          }
          var hassame = false;
          $.each(tableInterfaceJSON,function(i,fitem){
              if(fitem['key'].toLowerCase() === newdata['key'].toLowerCase()){
                  hassame = true;
                  return false;
              }
          });
          if(hassame){
              zUtil.msg("Sql编码不能相同");
              return false;
          }
          tableInterfaceJSON.push(newdata);
          //更新
          zUtil.val(IdDlgRightOpen + " #tableInterface", zUtil.strify(tableInterfaceJSON));
          
          //重新打开
          dlgConfig('RE1');
        },function(){
          zUtil.dialogClose('#dlg-add-sqlinterface');
        }];
    zUtil.dialogInit('#dlg-add-sqlinterface',dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen('#dlg-add-sqlinterface');
}
function configForTableRefreshTableCols(){
    var rowLeft = getTableLeft();
    if(rowLeft == null){
        return false;
    };
    var tableall = zUtil.treegrid(IdTableConfigTbl,'getdt');
    var tblMap = {};
    $.each(tableall,function(i,item){
        tblMap[item['tableCode'].toLowerCase()] = item;
    });
    var templateall = zUtil.tableData(IdTableConfigTemplate)["rows"];
    var okfunc = function(){
        var tblcols = zUtil.ajaxGetSync(zGlobal["http"] + "/api/autocode/table/columnlist", { projectId: rowLeft['projectId']});
        var resdata = tblcols[zConst["resData"]][zConst["data"]];
        if(resdata){
           var colsMap = {};
           var oldTabledata = {};
           for(var i=0; i< resdata.length; i++){
                var  d = resdata[i];
                var oldtable = tblMap[d['tableCode'].toLowerCase()];
                if(oldtable){
                    var oTableJavaCode = oldtable['tableJavaCode'].toLowerCase();
                    oldtable['tableTitle'] = d['tableTitle'];
                    oldtable['tableName'] = d['tableName'];
                    oldtable['tableAlias'] = d['tableAlias'];
                    oldtable['tableJavaCode'] = d['tableJavaCode'];
                    oldtable['tableJavaFullCode'] = d['tableJavaFullCode'];
                    
                    var allcols = d["columnInfos"];
                    if(allcols && allcols.length>0){
                        var ownEntity = [];
                        $.each(allcols,function(coli,colitem){
                            ownEntity.push({
                              columnCode: colitem['columnCode'],
                              columnName: colitem['columnName'],
                              columnTitle: colitem['columnTitle'],
                              columnJavaCode: colitem['columnJavaCode'],
                              columnJavaCode2: colitem['columnJavaCode'],
                              tableFlag: "1",
                              loadFlag: "1",
                              primarykeyFlag: colitem['columnPrimarykey'],
                              standardFlag: colitem['standardFlag'],
                              jdbcType: colitem['jdbcType'],
                              javaType: colitem['javaType'],
                              javaFullType: colitem['javaFullType'],
                              javaVoType: colitem['javaVoType'],
                            });
                            
                            colsMap[(d['tableCode']+'_'+colitem['columnCode']).toLowerCase()] = colitem;
                        });
                        oldtable['ownEntity'] = ownEntity;
                    }
                    
                    oldTabledata[oTableJavaCode] = oldtable;
                }
            }
            
           //和原始的表数据比较如果有则变化更新编码
           $.each(templateall,function(i,tag){
               var ot = oldTabledata[tag['fromKeyCode']];
               var tableFlag = tag['outputType'] === "4" || tag['outputType'] === "5";
               if(tableFlag && ot){
                    tag['fromKeyCode'] = ot['tableJavaCode'];
                    tag['quoteTag'] = tag['fromQuoteTag']+'_'+ tag['fromKeyCode'];
               }
           });
           
            //如果不能查询到则直接移除
            $.each(tableall,function(i,item){
                var tblWhereData = item['whereData'];
                if(tblWhereData && tblWhereData.length>0){
                    var whereData = [];
                    $.each(tblWhereData,function(idx,evo){
                        var tableCode = evo['tableCode'].toLowerCase();
                        if(tblMap[tableCode]){
                           var ncol = colsMap[(tableCode+'_'+evo['columnCode']).toLowerCase()];
                           if(ncol){
                               evo['columnCode'] = ncol['columnCode'];
                               if(!evo['columnJavaCode2'] || evo['columnJavaCode'] === evo['columnJavaCode2']){
                                   evo['columnJavaCode2'] = ncol['columnJavaCode'];
                               }
                               evo['columnTitle'] = ncol['columnTitle'];
                               evo['columnJavaCode'] = ncol['columnJavaCode'];
                               evo['tableAlias'] = ncol['tableAlias'];
                               evo['tableCode'] = ncol['tableCode'];
                               whereData.push(evo); 
                           }
                        }else{
                            whereData.push(evo);
                        }
                    });
                    item['whereData'] = whereData;
                }
                var sqlInterfaces = item['children'];
                if(sqlInterfaces && sqlInterfaces.length>0){
                    $.each(sqlInterfaces,function(j,sqlitem){
                        var oEntityData = sqlitem['entityData'];
                        var oWhereData = sqlitem['whereData'];
                        if(oEntityData && oEntityData.length>0){
                            var entityData = [];
                            $.each(oEntityData,function(idx,evo){
                                var tableCode = evo['tableCode'].toLowerCase();
                                if(tblMap[tableCode]){
                                   var ncol = colsMap[tableCode+'_'+evo['columnCode'].toLowerCase()];
                                   if(ncol){
                                       evo['columnCode'] = ncol['columnCode'];
                                       if(!evo['columnJavaCode2'] || evo['columnJavaCode'] === evo['columnJavaCode2']){
                                           evo['columnJavaCode2'] = ncol['columnJavaCode'];
                                       }
                                       evo['columnTitle'] = ncol['columnTitle'];
                                       evo['columnJavaCode'] = ncol['columnJavaCode'];
                                       entityData.push(evo); 
                                   }
                                }else{
                                   entityData.push(evo);
                                }
                            });
                            sqlitem['entityData'] = entityData;
                        }
                        if(oWhereData && oWhereData.length>0){
                            var whereData = [];
                            $.each(oWhereData,function(idx,evo){
                                var tableCode = evo['tableCode'].toLowerCase();
                                if(tblMap[tableCode]){
                                   var ncol = colsMap[tableCode+'_'+evo['columnCode'].toLowerCase()];
                                   if(ncol){
                                       evo['columnCode'] = ncol['columnCode'];
                                       if(!evo['columnJavaCode2'] || evo['columnJavaCode'] === evo['columnJavaCode2']){
                                           evo['columnJavaCode2'] = ncol['columnJavaCode'];
                                       }
                                       evo['columnTitle'] = ncol['columnTitle'];
                                       evo['columnJavaCode'] = ncol['columnJavaCode'];
                                       whereData.push(evo); 
                                   }
                                }else{
                                    whereData.push(evo);
                                }
                            });
                            sqlitem['whereData'] = whereData;
                        }
                    });
                }
                zUtil.treegrid(IdTableConfigTbl,'rfh',item['_uniqueId']);
            });
            
        }
        
    };
    zUtil.msgConfirm("仅同步表信息和实体字段，自定义部分不同步，若表/字段编码变更可先使用替换功能处理",okfunc);
}
function configForTableDel(fid){
    zUtil.treegrid(IdTableConfigTbl,'rmv',fid);
};

function configForTableEditStart(field,rowData){
    var rowIndex = rowData['_uniqueId'];
    if(TableInfoEditIndex && TableInfoEditIndex != rowIndex){
        zUtil.treegrid(IdTableConfigTbl,'ende',TableInfoEditIndex);
    }
    TableInfoEditIndex = rowIndex;
    if("checkbox" != field && "buttonArr" != field &&"tableCode" != field &&"tableTitle" != field 
       && !JsonReadonly){
        zUtil.treegrid(IdTableConfigTbl,'slt',rowIndex);
        zUtil.treegrid(IdTableConfigTbl,'begine',rowIndex);
    }else{
        zUtil.treegrid(IdTableConfigTbl,'ende',rowIndex);
    }
};
function configForTableEditReject(){
    if(TableInfoEditIndex){
        zUtil.treegrid(IdTableConfigTbl,'cancele',TableInfoEditIndex);
    }
}
//表关系
function configForTableRel(rowData){
    var tableFlag = (rowData['tableFlag']==="1");
    
    var tableRels = rowData['tableRels'];
    if(!tableRels){
        rowData['tableRels'] = [];
    }
    
    var options = {
            data : rowData['tableRels'],
            idField: '_uniqueId',
            toolbar: '#table-table-rel-toolbar',
            columns:[[
                {field: 'pColumnJavaCode', title: '主表字段', align: 'center', width: 250
                    , formatter: function(value,rowData,rowIndex){
                        return rowData['pTableJavaCode']+ ' . ' + value;
                    }},
                {field: 'cColumnJavaCode', title: '子表字段', align: 'center', width: 250
                    , formatter: function(value,rowData,rowIndex){
                        return rowData['cTableJavaCode']+ ' . ' + value;
                }},
                {field: ' ', title: ' ', align: 'center', width: 50},
            ]],
            frozenColumns:[[
             {field:'buttonArr', title:'操作', align:'center', width: 60,
                 formatter: function(value,rowData,rowIndex){
                   var btns = [];
                   btns.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="configForTableRelDel(\''+rowIndex+'\');" >删除</a>');
                   return btns.join(' ');
                }  },
            ]],
    };
    zUtil.tableInit2('#table-config-tbl-rel',options);
}
function configForTableRelAdd(){
    var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
    //未选中左侧表
    if(!tabledata){
        zUtil.msg("未选择右侧表数据");
        return false;
    }
    if(tabledata['tableFlag'] !== "1"){
        zUtil.msg("SQL无需配置该项");
        return false;
    }
    
    var stdata = [];
    var tableMaps = {};
    var defTableCode = null;
    var tableall = zUtil.treegrid(IdTableConfigTbl,'getdt');
    $.each(tableall,function(i,item){
        if(tabledata['tableCode'].toLowerCase() !== item['tableCode'].toLowerCase()){
            var trels = item['tableRels'];
            if(trels && trels.length>0){
               for(var j=0; j<trels.length; j++){
                 if(tabledata['tableCode'].toLowerCase() === trels[j]['cTableCode'].toLowerCase()){
                    return true;
                 }
               }
            }
            
            stdata.push({
                text: item['tableTitle'],
                value: item['tableCode']
            });
            if(defTableCode === null){
                defTableCode = item['tableCode'];
            }
        }
        tableMaps[item['tableCode'].toLowerCase()] = item;
   });
    
    //弹出选择
    var dlgSave = function(){
       var cTableCode = zUtil.val('#table-rel-toolbar-right #tableCode');
       var cTableDt = tableMaps[cTableCode];
       var ldata= zUtil.tableRows('#table-rel-colunms-left');
       var rdata= zUtil.tableRows('#table-rel-colunms-right');
       if(cTableCode && cTableDt && ldata && rdata && ldata.length>0 &&ldata.length === rdata.length){
           var relrow = zUtil.tableData('#table-config-tbl-rel')['rows'];
           var haskeys = {};
           $.each(relrow,function(i,item){
              var key = (item['pTableJavaCode']+item['pColumnJavaCode']
                          +item['cTableJavaCode']+item['cColumnJavaCode']).toLowerCase();
              haskeys[key] = "Y";
           })
           for(var i=0; i<ldata.length; i++){
               var t1 = ldata[i];
               var t2 = rdata[i];
               var key = (tabledata['tableJavaCode']+t1['columnJavaCode']
                           +cTableDt['tableJavaCode']+t2['columnJavaCode']).toLowerCase();
               if(haskeys[key]){
                   continue;
               }
               zUtil.table('#table-config-tbl-rel','apdrow',{
                  "_uniqueId": zUtil.uuid(),
                  "pTableCode": tabledata['tableCode'],
                  "pTableJavaCode": tabledata['tableJavaCode'],
                  "pColumnCode": t1['columnCode'],
                  "pColumnJavaCode": t1['columnJavaCode'],
                  "cTableCode": cTableDt['tableCode'],
                  "cTableJavaCode": cTableDt['tableJavaCode'],
                  "cColumnCode": t2['columnCode'],
                  "cColumnJavaCode": t2['columnJavaCode'],
               });
           }
           
           tabledata['tableRels'] = relrow;
           zUtil.Toastr("success","保存成功",null,{positionClass:"toast-top-center"});
       }else{
           zUtil.Toastr("error","未正确选择字段",null,{positionClass:"toast-top-center"}); 
       }
    };
    var dlgClose = function(){
      zUtil.dialogClose('#dlg-select-table-rel');
    };
    var dlgOptions = {
      title: '主子表关联字段配置',
      onOpen:function(){
          zUtil.inputInit($('#table-rel-toolbar-right #tableCode'),'select',{
              data : stdata,
              panelHeight: 250,
              onChange: function (nval, oval){
                  zUtil.tableData('#table-rel-colunms-right',tableMaps[nval]['ownEntity']);
              }
          });
          configForTableRelSelect('#table-rel-colunms-left','',tabledata['ownEntity']);
          configForTableRelSelect('#table-rel-colunms-right','#table-rel-toolbar-right',[]);
          zUtil.val('#table-rel-toolbar-right #tableCode',defTableCode);
          zUtil.tableUnSelected('#table-rel-colunms-left');
          zUtil.tableUnSelected('#table-rel-colunms-right');
      }
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    zUtil.dialogInit('#dlg-select-table-rel',dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen('#dlg-select-table-rel');
}
function configForTableRelDel(rowIndex){
    zUtil.tableSelected('#table-config-tbl-rel',rowIndex);
    var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
    tabledata['tableRels'] = zUtil.tableData('#table-config-tbl-rel')['rows'];
    zUtil.table('#table-config-tbl-rel','delrow',rowIndex);
}

function configForTableRelSelect(el,el2,data){
    var options = {
            data : data,
            idField: '_uniqueId',
            toolbar: el2,
            singleSelect:false,
            columns:[[
                {field:'checkbox',title:'',align:'center',width: 60,checkbox:true},
                {field: 'columnTitle', title: '字段标题', align: 'center', width: 150},
                {field: 'columnCode', title: '字段CODE', align: 'center', width: 150},
                {field: 'columnJavaCode', title: '驼峰编码', align: 'center', width: 150},
                {field: ' ', title: ' ', align: 'center', width: 50},
            ]],
    };
    zUtil.tableInit2(el,options);
}

//数据库对象配置-对象信息
function configForTableEntity(rowData){
    var tableFlag = (rowData['tableFlag']==="1");
    configForTableEntity2(IdTableTableEntity,true,tableFlag);
    configForTableEntity2(IdTableTableWhere,false,tableFlag);
    var entityData = rowData['entityData'];
    if(!entityData){
        rowData['entityData'] = [];
    }
    var whereData = rowData['whereData'];
    if(!whereData){
        rowData['whereData'] = [];
    }
    var tableData = rowData['tableData'];
    if(!tableData || tableData == null){
        rowData['tableData'] = "";
    }
    
    zUtil.val(IdTableTableEntityTb + ' #tableAlias',null);
    zUtil.val(IdTableTableWhereTb + ' #tableAlias',null);
    zUtil.val(IdTableTableDataTb + ' #tableAlias',null);
    zUtil.readonly(IdTableTableEntityTb + ' #tableAlias',false);
    zUtil.readonly(IdTableTableWhereTb + ' #tableAlias',false);
    zUtil.readonly(IdTableTableDataTb + ' #tableAlias',false);
    if(rowData['tableFlag'] === "1"){
        zUtil.val(IdTableTableDataTb + ' #tableAlias',rowData['tableAlias']);
        zUtil.val(IdTableTableEntityTb + ' #tableAlias',rowData['tableAlias']);
        zUtil.val(IdTableTableWhereTb + ' #tableAlias',rowData['tableAlias']);
        zUtil.readonly(IdTableTableEntityTb + ' #tableAlias');
        zUtil.readonly(IdTableTableWhereTb + ' #tableAlias');
        zUtil.readonly(IdTableTableDataTb + ' #tableAlias');
    }
    zUtil.elInit('#table-accordion','accordion-select',0);
    TableCodeEditor1.setValue(rowData['tableData']);
    if(!tableFlag){
        zUtil.tableData(IdTableTableEntity, rowData['entityData']);
    }else{
        zUtil.tableData(IdTableTableEntity, rowData['ownEntity']);
    }
    zUtil.tableData(IdTableTableWhere, rowData['whereData']);
}
function configForTableEntity2(el,flag,tableFlag){
    var options = {
            data : [],
            idField: '_uniqueId',
            toolbar: flag?IdTableTableEntityTb:IdTableTableWhereTb,
            columns:[[
                {field: 'columnCode', title: '字段CODE', align: 'center', width: 130},
                {field: 'tableCode', title: '表编码', align: 'center', width: 100, hidden: tableFlag},
                {field: 'tableAlias', title: ' 表别名', align: 'center', width: 100, hidden: tableFlag, editor:{type:'validatebox',options:{required:!tableFlag} }},
                {field: 'columnJavaCode', title: '驼峰编码', align: 'center', width: 100, editor:{type:'validatebox',options:{required:true} }  },
                {field: 'columnJavaCode2', title: '驼峰编码2', align: 'center', width: 100,editor:{type:'validatebox',options:{} }  },
                {field: 'conditionSymbol', title: '条件符号', align: 'center', width: 100, hidden: flag,formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"cfg.conditionSymbol");}
                   ,editor:{type:'combobox'
                    ,options:{panelHeight: 150, data: zUtil.dataFormat(zDictAutocode['cfg.conditionSymbol'],0)}} },
                {field: 'conditionSymbolType', title: '条件类型', align: 'center', width: 120, hidden: flag,formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"cfg.conditionSymbolType");}
                   ,editor:{type:'combobox'
                    ,options:{panelHeight: 150, data: zUtil.dataFormat(zDictAutocode['cfg.conditionSymbolType'],0)}} },
                {field: 'primarykeyFlag', title: '是否主键', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag");}
                  ,editor:{type:'combobox'
                    ,options:{panelHeight: 80,required:true, data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)}
                  }
                },
                {field: 'tableFlag', title: '当前表字段', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag");}
                  ,editor:{type:'combobox'
                    ,options:{panelHeight: 80,required:true, data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)}
                  }
                },
                {field: 'loadFlag', title: '引入到实体', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag");}
                  ,editor:{type:'combobox'
                    ,options:{panelHeight: 80,required:true, data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)}
                  }
                },
                {field: 'standardFlag', title: '标准类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag");}
                  ,editor:{type:'combobox'
                    ,options:{panelHeight: 80,required:true, data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)}
                  }
                },
                {field: 'jdbcType', title: 'JDBC类型', align: 'center', width: 100,editor:{type:'validatebox',options:{required:true}} },
                {field: 'javaType', title: 'JAVA类型', align: 'center', width: 100,editor:{type:'validatebox',options:{required:true}} },
                {field: 'javaFullType', title: 'JAVA类型(全)', align: 'center', width: 100,editor:{type:'validatebox',options:{required:true}} },
                {field: 'javaVoType', title: 'JAVA扩展类型', align: 'center', width: 100,editor:{type:'text',options:{required:true}} },
                {field: ' ', title: ' ', align: 'center', width: 150},
            ]],
            frozenColumns:[[
             {field:'buttonArr', title:'操作', align:'center', width: 60,hidden: (flag&&tableFlag)?true:JsonReadonly,
                 formatter: function(value,rowData,rowIndex){
                   var btns = [];
                   btns.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="configForTableEntityDel(\''+el+'\',\''+rowIndex+'\');" title="删除" ><i class="fa fa-trash"> </i></a>');
                   return btns.join(' ');
                }  },
             {field: 'columnTitle', title: '字段标题', align: 'center', width: 130},
            ]],
            onClickCell: function(rowIndex, field, value){
                tableEditForStart(field,rowIndex, flag?IdTableTableEntity:IdTableTableWhere);
            },
            loadFilter: function(data){
                if(data && data.length > 0){
                    $.each(data,function(i,item){
                        item['_uniqueId'] = zUtil.uuid();
                    });
                }
                return data;
             },
    };
    zUtil.tableInit2(el,options);
}
function configForTableEntityDel(el,rowIndex){
    zUtil.tableSelected(el,rowIndex);
    zUtil.table(el,'delrow',rowIndex);
    zUtil.tableData(el,zUtil.tableData(el));//重载
}
function configForTableEntityDelAll(type){
    var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
    if(tabledata['tableFlag'] === "1" && type==="1"){
        zUtil.msg("表主体无需使用该功能");
        return false;
    }
    zUtil.msgConfirm("清空全部字段?",function(){
        if(type==="1"){
           var data = [];
           zUtil.tableData(IdTableTableEntity, data);//重载
           tabledata['entityData'] = data;
        }else if(type==="2"){
           var data = [];
           zUtil.tableData(IdTableTableWhere, data);//重载
           tabledata['whereData'] = data;
        }
    });
}
//处理在线表编辑
CanUseTableDATA = {};
function configForTableEntityAdd(){
    if(JsonReadonly){
       return false;
    }
    
    var rowLeft = getTableLeft();
    if(rowLeft == null){
        return false;
    };
    zUtil.formClear(IdTableInfoTb);
    
    var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
    var tableAliasStr = zUtil.val(IdTableTableDataTb + ' #tableAlias');
    //未选中左侧表
    if(!tabledata){
        zUtil.msg("未选择左侧表或SQL");
        return false;
    }
    if(tabledata['tableFlag'] === "1"){
        zUtil.msg("表主体无需使用该功能");
        return false;
    }
    if(!tableAliasStr || tableAliasStr.trim().length===0){
        zUtil.msg("表别名必填,多表逗号分隔");
        return false;
    }
    
    var dlgSave = function(){
        var srows =  $.extend(true,[],zUtil.treegrid(IdTableInfo,"getsta"));
          if(srows && srows.length>0){
              var tableList =[];
              var tableMaps = {};
              $.each(srows,function(i,crow){
                  var tid = crow['tableCode'];
                  if(!tableMaps[tid]){
                      tableMaps[tid] = [];
                      tableList.push(tid);
                  }
                  if(!crow['tableId']){//选择的字段
                      tableMaps[tid].push(crow['columnCode']);
                  }
              });
              
              var tableAliasArr = tableAliasStr.split(",");
              if(tableList.length > tableAliasArr.length){
                  zUtil.msg("表别名必填,且对应表数量");
                  return false;
              }
              var sortTableMap = {};//表和顺序
              var tableAliasRelsMap = {};//表和别名
              $.each(tableList,function(i,item){
                  sortTableMap[item] = i;
                  tableAliasRelsMap[item] = tableAliasArr[i];
              });
              //主子表关联
              var allTableRels = [];
              var allTableRows = zUtil.treegrid(IdTableConfigTbl,'getdt');
              if(allTableRows&& allTableRows.length>0){
                  $.each(allTableRows,function(i,tblx){
                      var tableRels = tblx['tableRels'];
                      if(tableRels && tableRels.length>0){
                          allTableRels.push(...tableRels);
                      }
                  });
              }
              var tableRelsMap = {};
              $.each(allTableRels,function(j,relitem){
                  var pTableCode = relitem['pTableCode'];
                  var cTableCode = relitem['cTableCode'];
                  if(tableAliasRelsMap[pTableCode] && tableAliasRelsMap[cTableCode]){
                      if(sortTableMap[cTableCode] === 0){//放到主表
                           if(!tableRelsMap[pTableCode]){
                             tableRelsMap[pTableCode] = [];
                           }
                           tableRelsMap[pTableCode].push(tableAliasRelsMap[pTableCode] +"."+ relitem['pColumnCode']
                               +" = " + tableAliasRelsMap[cTableCode] +"."+ relitem['cColumnCode']);
                        }else if(sortTableMap[pTableCode] === 0){//放到子表
                           if(!tableRelsMap[cTableCode]){
                             tableRelsMap[cTableCode] = [];
                           }
                           tableRelsMap[cTableCode].push(tableAliasRelsMap[pTableCode] +"."+ relitem['pColumnCode']
                               +" = " + tableAliasRelsMap[cTableCode] +"."+ relitem['cColumnCode']);
                        }else{//放到子表
                           if(!tableRelsMap[cTableCode]){
                             tableRelsMap[cTableCode] = [];
                           }
                           tableRelsMap[cTableCode].push(tableAliasRelsMap[pTableCode] +"."+ relitem['pColumnCode']
                               + " = " + tableAliasRelsMap[cTableCode] +"."+ relitem['cColumnCode']);
                        }
                    }
             });
              
             var tblstr = TableCodeEditor1.getValue();
             var tblstr2 = tblstr?tblstr.toLowerCase().replace(/\n/g," "):null;
             var newtbl = [];
             var ti=0;
             $.each(tableMaps,function(key,item){
                 var tname = key+" "+ tableAliasArr[ti];
                 if(ti>0){
                     tname = 'LEFT JOIN ' + tname +' ON ';
                     var relstr = '';
                     if(tableRelsMap[key]){
                         relstr = tableRelsMap[key].join(' AND ');
                     }
                     if(item && item.length>0){
                         tname = tname + (relstr?relstr +' AND ':'') +tableAliasArr[ti]+"."+item.join("='' AND "+tableAliasArr[ti]+".")+" =''";
                     }else{
                         tname = tname + relstr;
                     }
                 }
                 newtbl.push(tname);
                 ti++;
             });
             TableCodeEditor1.setValue(tblstr +"\n"+ newtbl.join("\n"));
             
          }
          zUtil.dialogClose(IdDlgSelectTableInfo);
      };
      var dlgClose = function(){
        zUtil.dialogClose(IdDlgSelectTableInfo);
      };
      var dlgOptions = {
        title: '表选择',
      };
      var dlgButtonsIdx = [0,1];
      var dlgButtonsFunc =  [dlgSave,dlgClose];
      zUtil.dialogInit(IdDlgSelectTableInfo,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
      zUtil.dialogOpen(IdDlgSelectTableInfo);
      
      var options = {
              queryParams:{ projectId: rowLeft['projectId']},
              url : zGlobal["http"] + "/api/autocode/table/columnlist",
              idField: 'columnId',
              treeField:'columnTitle',
              sortName: 'orderNum',
              toolbar: IdTableInfoTb,
              singleSelect: false,
              columns:[[
                  {field: 'projectId', title: '所属项目', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT")}},
                  {field: 'tableId', title: '表主键ID', align: 'center', width: 100, hidden: true},
                  {field: 'columnId', title: '字段主键ID', align: 'center', width: 100, hidden: true},
                  {field: 'tableTag', title: '标签', align: 'center', width: 150},
                  {field: 'tableAlias', title: '表别名', align: 'center', width: 60},
                  {field: 'columnCode', title: '字段CODE', align: 'center', width: 200},
                  {field: 'columnJavaCode', title: '驼峰编码', align: 'center', width: 200},
                  {field: 'columnPrimarykey', title: '是否主键', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                  {field: 'columnMandatory', title: '是否为空', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                  {field: 'standardFlag', title: '标准类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                  {field: 'javaFullType', title: 'JAVA类型', align: 'center', width: 150},
                  {field: 'jdbcType', title: 'JDBC类型', align: 'center', width: 80},
                  {field: 'orderNum', title: '排序', align: 'center', width: 50},
                  {field: 'dataStatus', title: '状态', align: 'center', width: 50, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")}},
                  {field: ' ', title: ' ', align: 'center', width: 30},
              ]],
              frozenColumns:[[
                  {field:'', title:'', align:'center', width: 60, checkbox:true},
                  {field: 'columnTitle', title: '标题', align: 'left',halign: 'center', width: 200},
              ]],
              loadFilter: function(data){
                  var tmp = {rows:[],total:0};
                  try{//解析不了就原样返回
                      var ndata = data[zConst["resData"]][zConst["data"]];
                      if(ndata){
                          for(var i=0; i< ndata.length; i++){
                              var  d = ndata[i];
                              d["columnId"] = d['tableCode'];
                              d["columnCode"] = d['tableCode'];
                              d["columnTitle"] = d['tableTitle'];
                              d["columnJavaCode"] = d['tableJavaCode'];
                              d["columnJavaCode2"] = d['tableJavaFullCode'];
                              d["tableTag"] = d['tableTag'];
                              d["state"] = "closed";
                              var allcols = d["columnInfos"];
                              if(allcols && allcols.length>0){
                                  d["children"] = d["columnInfos"];
                                  d["columnInfos"] = null;
                              }
                              
                              var tcol =[];
                              if(allcols && allcols.length>0){
                                  $.each(allcols,function(i,item){
                                      tcol.push({
                                          "columnCode": item['columnCode'],
                                          "columnJavaCode": item['columnJavaCode']
                                      });
                                  });
                              }
                              CanUseTableDATA[d['tableCode']] = tcol;
                          }
                          tmp.rows = ndata;
                          tmp.total = data[zConst["resData"]][zConst["count"]];
                      }
                      
                  }catch(b){
                      return data;
                  }
                  return tmp;
               },
      };
      zUtil.treegridInit(IdTableInfo,options);
      zUtil.treegrid(IdTableInfo,"usta");
}

//编辑器
function configForTableCodeEditor1(){
    var rowLeft = getTableLeft();
    var alltblkeys ={};
    if(ConfigFirstFlag){
         var tblcols = zUtil.ajaxGetSync(zGlobal["http"] + "/api/autocode/table/columnlist", { projectId: rowLeft['projectId']});
         var resdata = tblcols[zConst["resData"]][zConst["data"]];//获取模板信息
         if(resdata){
             for(var i=0; i< resdata.length; i++){
                 var  d = resdata[i];
                 var tcol =[];
                 var allcols = d["columnInfos"];
                 if(allcols && allcols.length>0){
                     $.each(allcols,function(i,item){
                         tcol.push({
                             "columnCode": item['columnCode'],
                             "columnJavaCode": item['columnJavaCode']
                         });
                     });
                 }
                 CanUseTableDATA[d['tableCode']] = tcol;
                 alltblkeys[d['tableCode']] = [];
             }
         }
    }
    if(TableCodeEditor1 === null){
        TableCodeEditor1 = CodeMirror.fromTextArea($("#dlg-config-t2 #tableData")[0], {
              autoRefresh:true,
              lineNumbers: true,
              styleActiveLine: true,
              matchBrackets: true,
              lineWrapping: true,
//              indentWithTabs: true,
//              smartIndent: true,
//              autofocus: false,
//              tabSize: 4,
              mode:"text/x-hive",
              theme: 'dracula',
              extraKeys: { // 触发按键
              },
              hintOptions: {
                  completeSingle: false,  //关闭补全
                  tables: alltblkeys
              }
         });
        TableCodeEditor1.setSize('100%','100%');
        
        TableCodeEditor1.setOption("readOnly", JsonReadonly);
        
        TableCodeEditor1.on("change",function(){
            var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
            if(!tabledata){
                zUtil.msg("未选择左侧表或SQL");
                return false;
            }
            tabledata['tableData'] = TableCodeEditor1.getValue();
            
            configForTableSqlEditItem(alltblkeys);
        });
        TableCodeEditor1.on('keypress', () => {
            //编译器内容更改事件
            TableCodeEditor1.showHint();
        });
    }
    TableCodeEditor1.setValue('');
    if(ConfigFirstFlag){
        ConfigFirstFlag = false;
        TableCodeEditor1.setOption("hintOptions", {
            completeSingle: false,  //关闭补全
            tables: alltblkeys
        });
    }
}
function configForTableSqlEditItem(alltblkeys){
    var tTableKeys = "";
    var i=0;
    $.each(CanUseTableDATA,function(key,val){
        tTableKeys += i==0?key:"|"+key;
        i++;
    });
    if(tTableKeys && tTableKeys.trim().length>0){
        var ntblstr = TableCodeEditor1.getValue();
        if(ntblstr&& ntblstr.trim().length>0){
            ntblstr = ntblstr.replace('\\n'," ").replace(' +',' ');
            
            var regs =new RegExp("\\b("+tTableKeys+") +[A-Za-z]+[0-9]*","g");
            var farr = ntblstr.match(regs);
            if(farr && farr.length>0){
               var needTbls = {};
               $.each(farr,function(i,item){
                 var tkeys = item.split(' ');
                 var htbl = CanUseTableDATA[tkeys[0]];
                 if(htbl){
                     var fieldArr =[];
                     $.each(htbl,function(i,fv){
                         needTbls[fv['columnJavaCode']] = [];
                         needTbls[tkeys[1]+"."+fv['columnCode']] = [];
                     });
                 }
               });
               var  ohopts = TableCodeEditor1.getOption("hintOptions");
               setTimeout(function(){
                   TableCodeEditor1.setOption("hintOptions", 
                     {
                       completeSingle: false,  //关闭补全
                       tables: $.extend(true,{},alltblkeys, needTbls)
                     }
                   );
               }, 400);
            }
        }
    }
}
function configForTableEntityAdd2(addtype){
    var rowLeft = getTableLeft();
    if(rowLeft == null){
        return false;
    };
    var tabledata = zUtil.treegrid(IdTableConfigTbl,'getst');
    if(!tabledata){
        zUtil.msg("未选择左侧表或SQL");
        return false;
    }
    if(tabledata['tableFlag'] === "1" && addtype ==="1"){
        zUtil.msg("表主体无需使用该功能");
        return false;
    }
    
    var parentdata = zUtil.treegrid(IdTableConfigTbl,'find',tabledata['_parentId']);
    if(!parentdata){
        parentdata = tabledata;
    }
    var evo = [];
    var tableAliasStr = null;
    var IdTableTableEl = null;
    if(addtype ==="1"){
        evo = tabledata['entityData'];
        tableAliasStr = zUtil.val(IdTableTableEntityTb + ' #tableAlias');
        IdTableTableEl = IdTableTableEntity;
    }else if(addtype ==="2"){
        evo = tabledata['whereData']; 
        tableAliasStr = zUtil.val(IdTableTableWhereTb + ' #tableAlias');
        IdTableTableEl = IdTableTableWhere;
    }
    
    if(!tableAliasStr || tableAliasStr.trim().length ===""){
        zUtil.msg("表别名必填,多表逗号分隔");
        return false;
    }
    if(tabledata['tableFlag'] === "1" && addtype ==="2"){
        zUtil.val(IdTableTableEntityTb,tabledata['tableCode']);
    }
    
    
    var params = {};
    var dlgSave = function(){
      var srows =  $.extend(true,[],zUtil.treegrid(IdTableColumns,"getsta"));
      
      var getNode = function(crow){
      return {
              _uniqueId: zUtil.uuid(),
              columnTitle: crow['columnTitle'],
              columnCode: crow['columnCode'],
              columnJavaCode: crow['columnJavaCode'],
              columnJavaCode2: crow['columnJavaCode2']?crow['columnJavaCode2']:crow['columnJavaCode'],
              primarykeyFlag: crow['columnPrimarykey']?crow['columnPrimarykey']:"0",
              standardFlag: crow['standardFlag']?crow['standardFlag']:"0",
              javaFullType: crow['javaFullType'],
              javaType: crow['javaType'],
              javaVoType: crow['javaVoType'], 
              jdbcType: crow['jdbcType'],
              tableCode: crow['tableCode'],
              tableAlias: "",
              tableFlag: "1",
              loadFlag: "0",
              conditionSymbol:"eq",
             };
      };
      if(srows!=null && srows.length>0){
         var datas =[];
         var tables = {};
         var tableMaps = {};
         $.each(srows,function(i,crow){
             var node = getNode(crow);
             if(crow['tableId']){//选择的对象
                 datas = ($.extend(true,datas,crow['children']));
                 tableMaps[crow['tableCode']] = "Y";
             }else{//选择的字段
                 if(!tableMaps[crow['tableCode']]){
                     datas.push(crow);
                 }
             }
             if(!tables[crow['tableCode']]){
                 tables[crow['tableCode']] = "Y";
             }
         });
         
         
         if(datas.length>0){
             var tableAliasArr = tableAliasStr.split(",");
             var i = 0;
             $.each(tables,function(key, val){
                 tables[key] = tableAliasArr[i];
                 i++;
             });
             
             if(tables.length > tableAliasArr.length){
                 zUtil.msg("表别名必填,且对应表数量");
                 return false;
             }
             
             $.each(datas,function(key,item){
                 var node = getNode(item);
                 if(node['tableCode'] !== parentdata['tableCode']){
                     node['tableFlag'] = "0";
                     node['loadFlag'] = "1";
                 }
                 node['tableAlias'] = tables[node['tableCode']];
                 zUtil.table(IdTableTableEl,'apdrow', node);
             });
         }
      }
      
      
      if(addtype === "1"){
          tabledata['entityData'] = zUtil.tableData(IdTableTableEntity)['rows'];
      }else if(addtype === "2"){
          tabledata['whereData'] = zUtil.tableData(IdTableTableWhere)['rows'];
      }
      
      zUtil.dialogClose(IdDlgSelectTableCols);
    };
    var dlgClose = function(){
      zUtil.dialogClose(IdDlgSelectTableCols);
    };
    var dlgOptions = {
      title: '配置表字段',
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    zUtil.dialogInit(IdDlgSelectTableCols,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen(IdDlgSelectTableCols);
    
    var optionsEntity = {
            queryParams:{ projectId: rowLeft['projectId']},
            url : zGlobal["http"] + "/api/autocode/table/columnlist",
            idField: 'columnId',
            treeField:'columnTitle',
            sortName: 'orderNum',
            toolbar: IdTableColumnsTb,
            singleSelect: false,
            columns:[[
                {field: 'projectId', title: '所属项目', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT")}},
                {field: 'tableId', title: '表主键ID', align: 'center', width: 100, hidden: true},
                {field: 'columnId', title: '字段主键ID', align: 'center', width: 100, hidden: true},
                {field: 'tableTag', title: '标签', align: 'center', width: 150},
                {field: 'tableAlias', title: '表别名', align: 'center', width: 60},
                {field: 'columnCode', title: '字段CODE', align: 'center', width: 200},
                {field: 'columnJavaCode', title: '驼峰编码', align: 'center', width: 200},
                {field: 'columnPrimarykey', title: '是否主键', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'columnMandatory', title: '是否为空', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'standardFlag', title: '标准类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'javaFullType', title: 'JAVA类型', align: 'center', width: 150},
                {field: 'jdbcType', title: 'JDBC类型', align: 'center', width: 80},
                {field: 'orderNum', title: '排序', align: 'center', width: 50},
                {field: 'dataStatus', title: '状态', align: 'center', width: 50, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")}},
                {field: ' ', title: ' ', align: 'center', width: 30},
            ]],
            frozenColumns:[[
                {field:'', title:'', align:'center', width: 60, checkbox:true},
                {field: 'columnTitle', title: '标题', align: 'left',halign: 'center', width: 200},
            ]],
            loadFilter: function(data){
                var tmp = {rows:[],total:0};
                try{//解析不了就原样返回
                    var ndata = data[zConst["resData"]][zConst["data"]];
                    if(ndata){
                        for(var i=0; i< ndata.length; i++){
                            var  d = ndata[i];
                            d["columnId"] = d['tableCode'];
                            d["columnCode"] = d['tableCode'];
                            d["columnTitle"] = d['tableTitle'];
                            d["columnJavaCode"] = d['tableJavaCode'];
                            d["columnJavaCode2"] = d['tableJavaFullCode'];
                            d["tableTag"] = d['tableTag'];
                            d["state"] = "closed";
                            var allcols = d["columnInfos"];
                            if(allcols && allcols.length>0){
                                d["children"] = d["columnInfos"];
                                d["columnInfos"] = null;
                            }
                        }
                        tmp.rows = ndata;
                        tmp.total = data[zConst["resData"]][zConst["count"]];
                    }
                }catch(b){
                    return data;
                }
                return tmp;
             },
    };
    zUtil.treegridInit(IdTableColumns,optionsEntity);
    zUtil.treegrid(IdTableColumns,"usta");
  }

  //TODO
  function tableEditForStart(field, rowIndex, IdTableConfigEl){
      if(IdTableConfigEdit != IdTableConfigEl || IdTableConfigEditIdx != rowIndex){
          tableEditForAccept();
      }
      IdTableConfigEdit = IdTableConfigEl;
      IdTableConfigEditIdx = rowIndex;
      if("checkbox" != field && "buttonArr" != field && "methodKey" != field &&"quoteTag" != field 
        && "fileTitle" != field &&"outputFileFormat" != field &&"outputType" != field 
        && "columnTitle" != field && "columnCode" != field && !JsonReadonly){
          zUtil.tableUnSelected(IdTableConfigEdit);
          zUtil.tableSelected(IdTableConfigEdit,rowIndex);
          zUtil.table(IdTableConfigEdit,'begine',rowIndex);
      }else{
        tableEditForAccept();
      }
  }
  function tableEditForAddOfMethod(){
      var dlgOptions = {
                 title: '新增方法',
                 width: 500,
                 height: 300,
                 onOpen:function(){
                     zUtil.formClear('#dlg-add-method');
                 }
         };
      var dlgButtonsIdx = [0,1];
      var dlgButtonsFunc =  [function(){
            if(!zUtil.formCheck('#dlg-add-method')){
                return false;
            }
            zUtil.dialogClose('#dlg-add-method');
            var newdata = zUtil.valAll('#dlg-add-method');
            var attrFunctionKeyJSON = zUtil.parse(zUtil.val(IdDlgRightOpen + " #functionKey"));
            if(!attrFunctionKeyJSON){
                attrFunctionKeyJSON = {attrFunc:[]};
            }
            var attrFunc = zUtil.getVal(attrFunctionKeyJSON,"attrFunc");
            if(!attrFunc){
                attrFunc = [];
            }
            var hassame = false;
            $.each(attrFunc,function(i,fitem){
                if(fitem['key'].toLowerCase() === newdata['key'].toLowerCase()){
                    hassame = true;
                    return false;
                }
            });
            if(hassame){
                zUtil.msg("方法编码不能相同");
                return false;
            }
            attrFunc.push(newdata);
            attrFunctionKeyJSON['attrFunc'] = attrFunc;
            //更新
            zUtil.val(IdDlgRightOpen + " #functionKey", zUtil.strify(attrFunctionKeyJSON));
            
            //重新打开
            dlgConfig('RE1');
          },function(){
            zUtil.dialogClose('#dlg-add-method');
          }];
      zUtil.dialogInit('#dlg-add-method',dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
      zUtil.dialogOpen('#dlg-add-method');
  }
  //TODO
  function tableEditForAccept(obj){
      if('undefined' !== $.type(obj)){
          tableEditForGetEl(obj);
      }
      if (IdTableConfigEdit == null || IdTableConfigEditIdx == null){return true};
      var flag = zUtil.table(IdTableConfigEdit,'vldrow',IdTableConfigEditIdx);
      if (flag){
          zUtil.table(IdTableConfigEdit,'accepte');
          return true;
      } else {
          tableEditForReject();
          zUtil.Toastr("warn","缺少必填项",null,{positionClass:"toast-top-center"});
          return false;
      }
  }
  //TODO
  function tableEditForReject(){
      if(IdTableConfigEdit!=null){
         zUtil.table(IdTableConfigEdit,'rejecte');
      }
  }
  //TODO
  function tableEditForGetEl(obj){
      var el = $(obj.currentTarget);
      var IdTableConfigEditx = null;
      
      if(el.parents('.datagrid-toolbar').next().find(IdTableConfigMethod).length>0){
          IdTableConfigEditx = IdTableConfigMethod;
      }else if(el.parents('.datagrid-toolbar').next().find(IdTableConfigTbl).length>0){
          IdTableConfigEditx = IdTableConfigTbl;
      }
      
      if(IdTableConfigEdit && IdTableConfigEdit !== IdTableConfigEditx){
        tableEditForReject();
        IdTableConfigEditIdx = null;
      }
      IdTableConfigEdit = IdTableConfigEditx;
  }
  //更新模板信息
  function tableEditForUpdate(data){
      var selectRows = zUtil.tableRows(IdTableConfigEdit);
      if(selectRows!=null && selectRows.length>0){
         $.each(selectRows,function(i,item){
           IdTableConfigEditIdx = zUtil.table(IdTableConfigEdit,'getidx', item);
           
           if(IdTableConfigEdit != null && IdTableConfigEditIdx != null){
               var param = {
                     index: IdTableConfigEditIdx,
                     row: data
               }
               zUtil.table(IdTableConfigEdit,'updrow',param);
               zUtil.table(IdTableConfigEdit,'rfhrow',IdTableConfigEditIdx);
               tableEditForAccept();
           }
         });
      }else{
          zUtil.Toastr("warn","未选中",null,{positionClass:"toast-top-center"});
      }
      IdTableConfigEdit = null;
      IdTableConfigEditIdx = null;
  }
  
  //新增表
  function configForTableAddTable(){
    var rowLeft = getTableLeft();
    if(rowLeft == null){
        return false;
    };
    zUtil.formClear(IdTableInfoTb);
    
    
    var tableInterfaceJSON = $.extend(true,[],zUtil.parse(zUtil.val(IdDlgRightOpen +" #tableInterface")));
    
    var dlgSave = function(){
        var tabledata = zUtil.treegrid(IdTableConfigTbl,'getdt');
        var hasmap = {};
        $.each(tabledata,function(i,item){
            hasmap[item['tableCode'].toLowerCase()] = "Y";
        });
        
        var srows = zUtil.tableRows(IdTableInfo);
        if(srows && srows.length>0){
            var datas =[];
            $.each(srows,function(i,item){
                var tableCode = item['tableCode'].toLowerCase();
                if(hasmap[tableCode]){
                
                }else{
                    var tableInterfaceJSON2 = [];
                    $.each(tableInterfaceJSON,function(i,item){
                       tableInterfaceJSON2.push({
                           _uniqueId: zUtil.uuid(),
                           tableTitle: item['title'],
                           tableCode: item['key'],
                           tableJavaCode: item['code'],
                           needFlag: "1",
                           tableFlag: "0",
                           sqlGenerateType:"1",
                           iconCls: "fa fa-circle",
                           tableData: null,
                           entityData: null,
                           whereData: null,
                       });
                    });
                    
                    var row = {
                            _uniqueId: zUtil.uuid(),
                            tableTitle: item['tableTitle'],
                            tableCode: item['tableCode'],
                            tableName: item['tableName'],
                            tableAlias: item['tableAlias'],
                            tableJavaCode: item['tableJavaCode'],
                            tableJavaFullCode: item['tableJavaFullCode'],
                            needFlag: "1",
                            selectTemplate: SelectTemplateTable.toString(),
                            iconCls: "fa fa-database",
                            tableFlag: "1",
                            children: tableInterfaceJSON2,
                            state:"closed"
                    };
                    
                    var ownEntity = [];
                    if(item["columnInfos"]){
                        $.each(item["columnInfos"],function(coli,colitem){
                           ownEntity.push({
                             columnCode: colitem['columnCode'],
                             columnName: colitem['columnName'],
                             columnTitle: colitem['columnTitle'],
                             columnJavaCode: colitem['columnJavaCode'],
                             columnJavaCode2: colitem['columnJavaCode'],
                             tableFlag: "1",
                             loadFlag: "1",
                             primarykeyFlag: colitem['columnPrimarykey'],
                             standardFlag: colitem['standardFlag'],
                             jdbcType: colitem['jdbcType'],
                             javaType: colitem['javaType'],
                             javaFullType: colitem['javaFullType'],
                             javaVoType: colitem['javaVoType'],
                           });
                        });
                        row['ownEntity'] = ownEntity;
                    }
                    
                    datas.push(row);
                }
            });
            zUtil.treegrid(IdTableConfigTbl,'apd',{data: datas});
        }
        
        zUtil.dialogClose(IdDlgSelectTableInfo);
    };
    var dlgClose = function(){
      zUtil.dialogClose(IdDlgSelectTableInfo);
    };
    var dlgOptions = {
      title: '表选择',
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    zUtil.dialogInit(IdDlgSelectTableInfo,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen(IdDlgSelectTableInfo);
    
    var options = {
            queryParams:{projectId: rowLeft['projectId']},
            url : zGlobal["http"] + "/api/autocode/table/columnlist",
            idField: 'tableCode',
            sortName: 'orderNum',
            toolbar: IdTableInfoTb,
            singleSelect: false,
            columns:[[
                {field: 'projectId', title: '所属项目', align: 'center', width: 150, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT")}},
                {field: 'tableTag', title: '标签', align: 'center', width: 180},
                {field: 'tableCode', title: '表CODE', align: 'center', width: 200},
//                {field: 'tableName', title: '表NAME', align: 'center', width: 200},
                {field: 'tableAlias', title: '表别名', align: 'center', width: 60},
                {field: 'tableJavaCode', title: '驼峰编码1', align: 'center', width: 100 },
                {field: 'tableJavaFullCode', title: '驼峰编码2', align: 'center', width: 100 },
                {field: 'orderNum', title: '排序', align: 'center', width: 50},
                {field: 'dataStatus', title: '状态', align: 'center', width: 50, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")}},
                {field: ' ', title: ' ', align: 'center', width: 30},
            ]],
            frozenColumns:[[
               {field:'', title:'', align:'center', checkbox:true},
               {field: 'tableTitle', title: '标题', align: 'center', width: 150},
            ]],
    };
    zUtil.tableInit(IdTableInfo,options);
    zUtil.tableUnSelected(IdTableInfo);
  }
  function tableInfoQuery(){
      var rowLeft = getTableLeft();
      if(rowLeft == null){
          return false;
      };
      var param = zUtil.valAll(IdTableInfoTb);
      param['projectId'] = rowLeft['projectId'];
      var opts = zUtil.table(IdTableInfo, 'opts');
      if(opts.idField === "tableCode"){
          zUtil.tableQuery(IdTableInfo, param);
      }else{
          zUtil.treegrid(IdTableInfo,"load", param);
      }
  }
  function tableInfoClearSelect(){
      zUtil.tableUnSelected(IdTableInfo);
  }
  
  //TODO
  function createInputEl(options,elType){
      var opts = {
         text: "text",
         value: "value",
         method: "get"
      };
      opts = $.extend(true, opts, options.mores);
      var zcode = options.code;
      var ztitle = options.title;
      var ztype = options.type;
      var zloadtype = options.loadtype;
      var zdata = options.mores.data;
      var zlabel = opts.text;
      var zvalue = opts.value;
      var zmethod = opts.method;
      var zinputobj = null;
      
      if(elType =="1"){//横向
          zinputobj = {field: zcode, title: ztitle, align: 'center', width: 100,
//                  styler: function(value,row,index){
//                      return 'color:red;';// return {class:'c1',style:'color:red'}
//                  }
          };
      }else if(elType =="2"){//纵向
          zinputobj = {value: null,name: ztitle,field: zcode, title: ztitle,group:'扩展属性',
          };
      }
      
      if(ztype == "1"){
         var datas = getSwitchData();
         if(elType =="1"){
           zinputobj.formatter = function(value,rowData,rowIndex){
             return getSelectDataDesc(datas,value,opts);
           };
         }else if(elType =="2"){
           zinputobj["value"] = "0";
         }
         zinputobj.editor = {type:'switchbox', options:{
              value:"0",data: datas
           }
         };
      }else if(ztype == "2"){
         zinputobj.editor = {type:'text'};
      }else if(ztype == "3" || ztype == "4"){
         var datas = getSelectData(zloadtype,zdata,zmethod,opts);
         if(elType =="1"){
            zinputobj.formatter = function(value,rowData,rowIndex){ 
              return getSelectDataDesc(datas,value,opts); 
            };
         }else if(elType =="2"){
           if(datas !== null){
             zinputobj["value"] = datas[0][zvalue];
           }
         }
         
         zinputobj.editor = {type:'combobox',options:{
             valueField: zvalue, textField: zlabel, data: datas,
             panelHeight: ztype == "4"?300:200,
             multiple: ztype == "4"?true:false, 
           }
         };
      }else if(ztype == "5"){
          zinputobj.editor = {type:'textarea'};
       }
      return zinputobj;
  }
  function getSelectData(loadtype, data, method, opts){
      try{
          if(loadtype == "data" && data){
              return zUtil.parse(data);
          }else if(loadtype == "url" && data && method){
            var adata = null;
            if(method.toUpperCase() === "GET"){
                adata = zUtil.ajaxGetSync(data);
            }else if(method.toUpperCase() === "POST"){
                adata = zUtil.ajaxPostSync(data);
            }
            if($.type(adata) === "object" && adata[zConst['resData']]){
                adata = adata[zConst['resData']];
            }
            else if($.type(adata) === "object" && adata['data']){
                adata = adata['data'];
            }
            else if($.type(adata) === "object" && adata['result']){
                adata = adata['result'];
            }
            else if($.type(adata) === "object" && adata['list']){
                adata = adata['list'];
            }
            if($.type(adata) === "object" && adata['data'] && $.type(adata['data']) === "array"){
                adata = adata['data'];
            }else if($.type(adata) === "object" && adata['list'] && $.type(adata['list']) === "array"){
                adata = adata['list'];
            }
            if(adata && $.type(adata) === "array"){
                return adata;
            }
            return [];
          }
      }catch(b){
           console.info("获取扩展属性字典错误>>"+data);
      }
  };
  function getSelectDataDesc(data,value,options){
      var labelCode = "text";
      var valueCode = "value";
      if("undefined" !== $.type(options)){
          labelCode = options.text;
          valueCode = options.value;
      }
      if(data != null){
          var dataobj ={};
          for(var i=0;i<data.length; i++){
            dataobj[data[i][valueCode]] = data[i][labelCode];
          }
          var desc =[];
          if(value){
              var vals = value.toString().split(",");
              for(var j=0;j<vals.length;j++){
                if(dataobj[vals[j]]){
                  desc.push(dataobj[vals[j]]);
                }
              }
              if(desc.length>0){
                return desc.join(",");
              }
          }
      }
      if(value == null){
          value = "";
      }
      return value;
  };
  function getSwitchData(){
    return [{"value":"0","text":"否"}, {"value":"1","text":"是"}];
  }
  function showWholePath(newValue, oldValue){
    var showstr ="";
    var outputBasePathVal = zUtil.val(IdTableConfigTemplateShow + " #outputBasePath");
    if(outputBasePathVal != null){
      showstr = showstr + outputBasePathVal +"/"
    }
    var outputPathVal = zUtil.val(IdTableConfigTemplateShow + " #outputPath");
    if(outputPathVal != null){
      showstr = showstr + outputPathVal +"/"
    }
    var outputFileNameVal = zUtil.val(IdTableConfigTemplateShow + " #outputFileName");
    showstr = showstr + outputFileNameVal + '.' + zUtil.val(IdTableConfigTemplateShow + " #outputFileFormat");
    $(IdTableConfigTemplateShow + " [name='wholePath']").html(showstr);
  }
  function showParamsList(){
    var htmlStr = '<tr style="color: red;">'
    + '<td style="" colspan="2">【模块变量A_】适用模板类型：模块、方法、表</td>'
    + '</tr>';
    $.each(ObjParamConfig1,function(i,item){
        htmlStr = htmlStr + '<tr style="">'
        + '<td style="width: 130px;">'+item['title']+'</td><td><span id="A_'+i+'">{A_'+item['code']+'}</span><span class="js-copy fa fa-files-o" data-clipboard-target="#A_'+i+'"></span></td>'
        + '</tr>';
    });
    var htmlStr2 = '<tr style="color: red;">'
        + '<td style="" colspan="2">【方法变量B_】适用模板类型：方法</td>'
        + '</tr>';
    $.each(ObjParamConfig2,function(i,item){
            htmlStr2 = htmlStr2 + '<tr style="">'
            + '<td style="width: 130px;">'+item['title']+'</td><td><span id="B_'+i+'">{B_'+item['code']+'}</span><span class="js-copy fa fa-files-o" data-clipboard-target="#B_'+i+'"></span></td>'
            + '</tr>';
    });
    var htmlStr3 = '<tr style="color: red;">'
        + '<td style="" colspan="2">【方法变量C_】适用模板类型：表</td>'
        + '</tr>';
    $.each(ObjParamConfig3,function(i,item){
            htmlStr3 = htmlStr3 + '<tr style="">'
            + '<td style="width: 130px;">'+item['title']+'</td><td><span id="C_'+i+'">{C_'+item['code']+'}</span><span class="js-copy fa fa-files-o" data-clipboard-target="#C_'+i+'"></span></td>'
            + '</tr>';
    });
    var htmlStr7 = '<tr style="color: red;">'
        + '<td style="" colspan="2">【对象变量D_】适用模板类型：子对象</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td style="width: 130px;">驼峰编码</td><td><span id="D_0">{D_fieldJavaCode}</span><span class="js-copy fa fa-files-o" data-clipboard-target="#D_0"></span></td>'
        + '</tr>'
        ;
    htmlStr = htmlStr+ htmlStr2 + htmlStr3 + htmlStr7;
    $(IdDlgUsePath + ' #table1>tbody').html(htmlStr);
    
    
    var htmlStr4 = '<tr style="color: red;">'
        + '<td style="" colspan="2">在路径中使用加上前缀(A_,B_,C_,D_)，模板内使用没有前缀</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td colspan="2">首字母大写加U，{UA_XXX}</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td colspan="2">首字母小写加L，{LA_XXX}</td>'
        + '</tr>';
    $(IdDlgUsePath + ' #table4>tbody').html(htmlStr4);
    
    
    var htmlStr5 = '<tr style="color: red;">'
        + '<td style="" colspan="2">常用的一些需手动引入的Java类,配置在字典cfg.useJavaClass中</td>'
        + '</tr>';
    var useJavaClassVal = zDictAutocode['cfg.useJavaClass'];
    if(useJavaClassVal){
        var i=0;
        $.each(useJavaClassVal,function(key,value){
            htmlStr5 = htmlStr5 + '<tr style="">'
            + '<td style="width:130px;">'+key+'</td><td><span id="useJavaClass'+i+'">'+value+'</span><span class="js-copy fa fa-files-o" data-clipboard-target="#useJavaClass'+i+'"></span></td>'
            + '</tr>';
            i++;
        });
    }
    $(IdDlgUsePath + ' #table5>tbody').html(htmlStr5);
    
    var htmlStr6 = '<tr style="color: red;">'
        + '<td style="" colspan="2">可用于模板：import/resource/extends </td>'
        + '</tr>'
        +'<tr style="color: red;">'
        + '<td style="" colspan="2">可用于方法对象：java类型</td>'
        + '</tr>'
        +'<tr style="color: red;">'
        + '<td style="" colspan="2">可用于SQL：传入参数/返回参数</td>'
        + '</tr>'
        +'<tr style="color: red;">'
        + '<td style="" colspan="2">xx表示模板引用编码</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td colspan="2">文件名：{name_xx}，{uname_xx}/{lname_xx}首字母大/小写</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td colspan="2">路径：{pack_xx}，java为包路径,{pack2_xx}不带import，非java为文件路径</td>'
        + '</tr>'
        + '<tr style="">'
        + '<td colspan="2">文件层级：{level_xx}，根据基础路径计算，例../../</td>'
        + '</tr>'
        ;
    $(IdDlgUsePath + ' #table6>tbody').html(htmlStr6);
    
    
    
    var clipObj = zUtil.clip('.js-copy',{
        success:function(e) {
            zUtil.Toastr("success","已复制" + e.text);
            $(e.trigger).prev().select();
        }
    });
    
    var dlgClose = function(){
      clipObj.destroy();
      zUtil.dialogClose(IdDlgUsePath);
    };
    var dlgOptions = {
      title: '参数和说明',
      width: 500,
      height: 500,
      collapsible: true,
      modal: false,
      onClose:function() {
          clipObj.destroy();
      }
    };
    var dlgButtonsIdx = [1];
    var dlgButtonsFunc = [dlgClose];
    zUtil.dialogInit2(IdDlgUsePath,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);   
    zUtil.dialogOpen(IdDlgUsePath);
  }
  
  var InputDefaultData = null;
  var InputDataMap = {};
  var MethodChildEntityTemplates = null;
  //对象配置-对象信息
  function configForMethodEntity(templateRows,title,index){
      var leftRowData = getTableLeft();
      if(InputDefaultData === null){
        var detail = zUtil.ajaxGetSync(zGlobal["http"] + "/api/autocode/webComponent/list", {projectId: leftRowData['projectId'],"limit":200,"page":1});
        detail = zUtil.getVal(detail[zConst["resData"]],zConst["data"]);
        if(detail && detail.length > 0){
            $.each(detail,function(i,item){
                if(item['componentType'] === 'input'){
                    InputDefaultData = item;
                }
                InputDataMap[item['componentCode']] = item;
            });
        }
      };
      
      var excludeTemplateIdsVal = zUtil.val(IdDlgRightOpen + " #excludeTemplateIds");
      
      //模板处理
      var methodTemplates = [];
      var entityTemplatesMap = {};
      $.each(templateRows,function(i,item){
          var flag = excludeTemplateIdsVal == null || (excludeTemplateIdsVal != null && excludeTemplateIdsVal.indexOf(item['templateFileId'])<0);
          var outputType = item['outputType'];
          if(outputType === "6" && flag){
              var tt = {
                      "id": item['quoteTag'],
                      "text": item['quoteTag'],
                      "group": outputType,
                  };
              methodTemplates.push(tt);
          }
          if(outputType === "3" && flag){
              entityTemplatesMap[item['quoteTag']] = outputType;
          }
      });
      MethodChildEntityTemplates = methodTemplates;
      var onSelectFunc = function(node, checked){
          //展示数据
          var znode = $.extend(true,{},node);
          var zattr = znode.attributes;
          var treeEntityData = [];
          if("1" === zattr.zOprType){
             treeEntityData = [];
             $(IdTableConfigTabs).tabs("select",0);
             zUtil.tableSelected(IdTableConfigMethod,zattr['_uniqueId']);
          }else if("2" === zattr.zOprType){
              zUtil.tableSelected(IdTableConfigMethod,zattr['_uniqueId']);
              var methodx = zUtil.tableRows(IdTableConfigMethod);
              var entityData = methodx['entityData'];
              treeEntityData = entityData[zattr['tagKey']];
              if(!treeEntityData || treeEntityData.length === 0){
                  treeEntityData = [ {fieldTitle: zattr['methodKeyName'] +"-"+zattr['entityName'], fieldJavaCode: "ROOT", _leftId: znode.id, _uniqueId: zUtil.uuid()} ];
                  entityData[zattr['tagKey']] = treeEntityData;
              }else if(treeEntityData[0]['children']){
                 var childrenx = treeEntityData[0]['children'];
                 $.each(childrenx,function(idx,item){
                    if(item['children'] && item['children'].length>0){
                        item['state'] = "closed";
                    }
                 });
              }
          }
          zUtil.treegrid(IdTableTreeMethodEntity, "ldt", treeEntityData);
      };
      var onLoadSuccessFunc = function(node, data){
         var buttonsTreeEntity = function(value,rowData,rowIndex){
             var btsArr =[];
             btsArr.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="tableTreeEntityDel(\''+rowData['_uniqueId']+'\');" title="移除字段" ><i class="fa fa-remove"> </i></a>&nbsp;&nbsp;');
             btsArr.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="tableTreeEntityAdd1(\''+rowData['_uniqueId']+'\');" title="添加表字段" ><i class="fa fa-plus-circle">表</i></a>');
             btsArr.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="tableTreeEntityAdd2(\''+rowData['_uniqueId']+'\');" title="添加自定义字段" ><i class="fa fa-plus">字段</i></a>');
             btsArr.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="tableTreeEntityAdd3(\''+rowData['_uniqueId']+'\');" title="添加JSON" ><i class="fa fa-plus">JSON</i></a>');
             if(rowData.fieldJavaCode !== "ROOT"){
                 btsArr.push('<a href="javascript:void(0)" class="easyui-linkbutton" onclick="dlgEntityAttrOptions(\''+rowData['_uniqueId']+'\');" title="编辑" ><i class="fa fa-pencil">编辑</i></a>');
             }else{
                 btsArr.push('&nbsp;&nbsp;'); 
             }
             return btsArr.join("&nbsp;");
         };
         var attrExtendFieldJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #attrExtendField"));
         if(attrExtendFieldJSON == null){
           attrExtendFieldJSON = [];
         }
         var colsTreeEntity1 = [
                {title: '基础属性',colspan: 4, align: 'center'},
                {title: '后台属性',colspan: 5, align: 'center'},
                {title: '页面属性',colspan: 9, align: 'center'},
                {title: '校验属性',colspan: 4, align: 'center'},
                {field: 'fieldEx',title: '扩展属性', align: 'center',colspan: (attrExtendFieldJSON && attrExtendFieldJSON.length>0?attrExtendFieldJSON.length: 1)},
                {field:'__blank',title: ' ',width: 150,rowspan: 2},
             ];
         var colsTreeEntity = [
             {field: 'fieldJavaCode2', title: '驼峰编码2', align: 'center', width: 100, editor: {type:'text'} },
//             {field: 'fieldCode', title: '字段编码', align: 'center', width: 100, editor: {type:'text'}  },
             {field: 'fieldUseType', title: '使用范围', align: 'center', width: 120
                 , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.fieldUseType'],0), panelHeight: 200, multiple: false }}
                , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.fieldUseType")}},
             {field: 'fieldType', title: '字段类型', align: 'center', width: 120
                    , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['cfg.fieldType'],0), panelHeight: 200, multiple: false }}
                   , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"cfg.fieldType")}},
             {field: 'selectTemplate', title: '加载模板', align: 'center', width: 100,  editor: {type:'combobox', 
                 options:{valueField:'id',textField:'text',groupField: "group",panelHeight:150,data:methodTemplates
                    , groupFormatter: function(group){
                            return zUtil.dictConvertOfAutocode(group,"template.outputType");
                 }  }} },
//             {field: 'standardFlag', title: '标准类型', align: 'center', width: 80
//                     , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0), panelHeight: 80 }}
//                     , formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
             {field: 'useTableCode', title: '引用表编码', align: 'center', width: 150,editor: {type:'text'}  },
             {field: 'useTableSqlCode', title: '引用表SQL', align: 'center', width: 150,editor: {type:'text'}  },
             {field: 'useModuleCode', title: '引用模块', align: 'center', width: 130, editor: {type:'text'}  },
             {field: 'useMethodCode', title: '引用方法', align: 'center', width: 130, editor: {type:'text'}  },
             {field: 'javaType', title: 'JAVA类型', align: 'center', width: 80},
             {field: 'inputType', title: '组件类型', align: 'center', width: 100},
//             {field: 'componentType', title: '组件类型', align: 'center', width: 100},
             {field: 'inputNumber', title: '组件数量', align: 'center', width: 80, editor: {type:'text'}},
             {field: 'gridClonums', title: '栅格宽度', align: 'center', width: 80, editor: {type:'text'}},
             {field: 'inputDict', title: '组件字典', align: 'center', width: 100, editor: {type:'text'}},
             {field: 'inputClass', title: '组件样式', align: 'center', width: 80, editor: {type:'text'}},
             {field: 'pageOrder', title: '显示排序', align: 'center', width: 70, editor: {type:'text'}},
             {field: 'pageShowFlag', title: '显示标志', align: 'center', width: 70
                 , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0), panelHeight: 80 }}
                 , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
             {field: 'groupCode', title: '分组编码', align: 'center', width: 100, editor: {type:'text'}},
             {field: 'groupName', title: '分组名称', align: 'center', width: 100, editor: {type:'text'}},
             {field: 'mustFlag', title: '是否必填', align: 'center', width: 80
                 , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0), panelHeight: 80 }}
                 , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
             {field: 'readonlyFlag', title: '是否只读', align: 'center', width: 80
                     , editor: {type:'combobox',options:{ data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0), panelHeight: 80 }}
                     , formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
             {field: 'checkBackground', title: '后台校验', align: 'center', width: 100, editor: {type:'text'}},
             {field: 'checkPage', title: '页面校验', align: 'center', width: 100, editor: {type:'text'}},
             
         ];
         
         if(attrExtendFieldJSON && attrExtendFieldJSON.length>0){
             for(var i=0;i<attrExtendFieldJSON.length;i++){
                 var col = createInputEl(attrExtendFieldJSON[i],"1");
                 colsTreeEntity.push(col);
             }
         }else{
             colsTreeEntity.push({field: '__blank', title: ' ', width: 100});
         }
         
         var optionsTreeEntity = {
                 columns:[colsTreeEntity1,colsTreeEntity],
                 frozenColumns:[
                     [ {field:'buttonArr', title:'操作', align:'center', width: 250,hidden: JsonReadonly, formatter: buttonsTreeEntity,rowspan: 2 },
                       {title: '基础属性', align: 'center',colspan: 2}
                     ],
                     [ {field: 'fieldTitle', title: '字段标题', align: 'left',halign:"center", width: 170, editor: {type:'validatebox',options:{required:true}}  },
                       {field: 'fieldJavaCode', title: '驼峰编码', align: 'left',halign:"center", width: 170, editor: {type:'validatebox',options:{required:true}}  },
                     ]
                  ],
                 idField: '_uniqueId',
                 treeField: 'fieldTitle',
                 data: [],
                 onClickCell: function(field, rowData){
                     configForMethodEntityEditStart(field, rowData['_uniqueId']);
                 },
                 onClickRow: function(rowData){
                     var editObjs = zUtil.treegrid(IdTableTreeMethodEntity,"getEditors",rowData['_uniqueId'])
                     $.each(editObjs, function(idx,item){
                         if(rowData['fieldJavaCode'] === "ROOT"){
                             if(item.field === "fieldTitle" || item.field === "fieldJavaCode"){
                                 zUtil.readonly($(item.target));
                             }
                             else {
                                 $(item.target).css("display","none")
                                 $(item.target).next('span').css("display","none");
                                 zUtil.val($(item.target),null);
                             }
                         }else{
                             if(item.field === "selectTemplate"
                                 && rowData['fieldType'] !=="2" && rowData['fieldType'] !=="3"){
                                 $(item.target).css("display","none")
                                 $(item.target).next('span').css("display","none");
                                 zUtil.val($(item.target),null);
                             }
                         }
                     });
                 },
                 onAfterEdit: function(rowData, changes){
                     var inputDict = changes['inputDict'];
                     if($.type(inputDict) === "string"){//变更
                         configForMethodEntityChangeDict(inputDict);
                     }
                 },
         };
         
         
         zUtil.treegridInit2(IdTableTreeMethodEntity, optionsTreeEntity);
      };
      
      var onContextMenuFunc = function(e, node){
         e.preventDefault();
         zUtil.tree(IdTreeMainMethod,"slt",node.target);
         var zattr = node.attributes;
         if("1" === zattr.zOprType){
            return;
         }
         var menuEL = $('<div>'
               +'<div onclick="configForMethodEntityVoCopy(\''+node.id+'\')" data-options="iconCls:\'fa fa-files-o\'">拷贝对象</div>'
               +'<div onclick="configForMethodEntityVoPaste(\''+node.id+'\')" data-options="iconCls:\'fa fa-clipboard\'">粘贴对象</div>'
               +'<div onclick="configForMethodEntityJsonCopy(\''+node.id+'\')" data-options="iconCls:\'fa fa-files-o\'">拷贝JSON</div>'
               +'<div onclick="configForMethodEntityViewEdit(\''+node.id+'\')" data-options="iconCls:\'fa fa-eye\'">简易可视化</div>'
               +'</div>');
         // 显示快捷菜单
         zUtil.elInit(menuEL,"menu",{
             left: e.pageX,
             top: e.pageY
         });
      };
      
      zUtil.treeInit(IdTreeMainMethod,{
            data: [],
            cascadeCheck: false,
            onSelect: onSelectFunc,
            onLoadSuccess: onLoadSuccessFunc,
            onContextMenu: onContextMenuFunc
      });
      
      if(index === 3){ 
          var handleData = function(){
              var params2 = $.extend(true,[],zUtil.tableData(IdTableConfigMethod)["rows"]);
              var treedata = [];
              if(params2 != null && params2.length>0){
                  var cdata =[];
                  var treemethod = [];
                  for(var i=0; i<params2.length;i++){
                      var carr = params2[i];
                      var methodKey = carr['methodKey'];
                      var methodnode = {
                              "id": carr['_uniqueId'],
                              "text": carr['methodKeyName'] + "---" + carr['methodKey'],
                              "iconCls":"",
                              "attributes":{zOprType:"1",_uniqueId: carr['_uniqueId']},
                              "children":[],
                      };
                      var entityJSON = carr['entityData'];
                      var selectTemplateVal =  carr['selectTemplate'];
                      
                      var treetemplate =[];
                      
                      if(entityJSON && selectTemplateVal){
                          selectTemplateVal = selectTemplateVal.split(",");
                          $.each(selectTemplateVal,function(si,tagid){
                              if(entityTemplatesMap[tagid]){
                                  var entityVo = $.extend(true,{},entityJSON[tagid]);
                                  treetemplate.push({
                                      "id": tagid + "_" + methodKey,
                                      "text": tagid,
                                      "iconCls":"fa fa-file-text-o",
                                      "attributes":{
                                           zOprType:"2",
                                           entityName: tagid,
                                           tagKey: tagid,
                                           methodKey: methodKey,
                                           methodKeyName: carr['methodKeyName'],
                                           _uniqueId: carr['_uniqueId']
                                      },
                                  });
                              }
                          });
                      }
                      
                      methodnode['children'] = treetemplate;
                      treemethod.push(methodnode);
                  }
                  treedata = treemethod;
              }
              
              return treedata;
         };
         zUtil.tree(IdTreeMainMethod,'ldt', handleData());
         
      }else{ 
         zUtil.tree(IdTreeMainMethod,'ldt',[]);
         MethodEntityCopyIdx = null;
      }
  }
  function configForMethodEntityChangeDict(inputDict){
      var mainData = zUtil.tableData(IdTableConfigMain)["rows"];
      $.each(mainData,function(i,item){
        if(item.field === "loadDict"){
            if(inputDict && inputDict!=''){
                 if(item.value){
                    var arrs = item.value.split(',');
                    var hasDict = false;
                    $.each(arrs,function(j,item){
                        if(item && item.trim() === inputDict){
                            hasDict = true;
                            return false;
                        }
                    });
                    if(!hasDict){
                        item.value = item.value +"," +inputDict;
                    }
                 }else{
                    item.value = inputDict;
                 }
                 zUtil.table(IdTableConfigMain,'rfhrow',i);
            }
            return false;
        }
      });
  }
  function configForMethodEntityEditStart(field,rowIndex){
        if(MethodEntityEditIndex && MethodEntityEditIndex !== rowIndex){
            zUtil.treegrid(IdTableTreeMethodEntity,'ende', MethodEntityEditIndex);
        }
        MethodEntityEditIndex = rowIndex;
        if("checkbox" !== field && "buttonArr" !== field
           && !JsonReadonly){
            zUtil.treegrid(IdTableTreeMethodEntity,'slt',rowIndex);
            zUtil.treegrid(IdTableTreeMethodEntity,'begine',rowIndex);
        }else{
            zUtil.treegrid(IdTableTreeMethodEntity,'ende',rowIndex);
        }
  }
  function configForMethodEntityEditReject(){
      if(MethodEntityEditIndex){
          zUtil.treegrid(IdTableTreeMethodEntity,'cancele',MethodEntityEditIndex);
      }
  }
  
  function configForMethodEntityVoCopy(nodeId){
     MethodEntityCopyIdx = nodeId;
  }
  function configForMethodEntityVoPaste(nodeId){
    if(MethodEntityCopyIdx !== null && MethodEntityCopyIdx !== nodeId){
        var copyNode = $.extend(true,{},zUtil.tree(IdTreeMainMethod,"find",MethodEntityCopyIdx));
        var pasteNode = $.extend(true,{},zUtil.tree(IdTreeMainMethod,"find",nodeId));
        if(copyNode){
           var attr1 = copyNode['attributes'];
           var attr2 = pasteNode['attributes'];
           var okfunc = function(){
               zUtil.tableSelected(IdTableConfigMethod,attr1['_uniqueId']);
               var methodx1 = zUtil.tableRows(IdTableConfigMethod);
               var entityData1 = zUtil.getVal(methodx1,'entityData.'+attr1['tagKey']);
               
               var copydata = [ {fieldTitle: attr2['methodKeyName'] +"-"+attr2['entityName'], fieldJavaCode: "ROOT", _leftId: nodeId, _uniqueId: zUtil.uuid()} ];
               if(entityData1 && entityData1.length > 0){
                   copydata[0]['children'] = $.extend(true,[],entityData1[0]['children']);
               }
               
               zUtil.tableSelected(IdTableConfigMethod,attr2['_uniqueId']);
               var methodx2 = zUtil.tableRows(IdTableConfigMethod);
               var entityData2 = zUtil.getVal(methodx2,'entityData.'+attr2['tagKey']);
               if(entityData2 && entityData2.length > 0){
                   var ndt = $.extend(true,{},entityData2[0]);
                   if(ndt['children']){
                       delete ndt['children'];
                   }
                   methodx2['entityData'][attr2['tagKey']] = $.extend(true,copydata,ndt);
               }else{
                   methodx2['entityData'][attr2['tagKey']] = copydata;
               }
               
               zUtil.tree(IdTreeMainMethod,"slt",pasteNode.target);
           };
           var oldvoname = attr1['methodKeyName'] + "-"+ copyNode.text;
           var newvoname = attr2['methodKeyName'] + "-"+ pasteNode.text;
           zUtil.msgConfirm("复制【"+oldvoname+"】至【"+newvoname+"】", okfunc);
        }
    }
  }
  //对象JSON显示
  function configForMethodEntityJsonCopy(nodeId){
    zUtil.formClear(IdDlgMethodEntityJson1);
    
    var copyNode = $.extend(true,{},zUtil.tree(IdTreeMainMethod,"find",nodeId));
    var entityjson = "";
    if(copyNode){
        var attr1 = copyNode['attributes'];
        
        var doHandleData = function(data){
            if(data && data.length>0){
                $.each(data,function(i,item){
                    //不要
                    delete item['_parentId'];
                    delete item['checkState'];
                    delete item['checked'];
                    delete item['state'];
                    delete item['_leftId'];
                    
                    doHandleData(item['children']);
                });
            }
        };
        
        zUtil.tableSelected(IdTableConfigMethod,attr1['_uniqueId']);
        var methodx1 = zUtil.tableRows(IdTableConfigMethod);
        var entityData1 = zUtil.getVal(methodx1,'entityData.'+attr1['tagKey']);
        if(entityData1 && entityData1.length > 0 && entityData1[0]['children']){
            doHandleData(entityData1);
            entityjson = zUtil.strify(entityData1[0]['children'],{indentFlag: true}) +"\n";
        }
    }
   
    var dlgClose = function(){
      zUtil.dialogClose(IdDlgMethodEntityJson1);
    };
    var dlgOptions = {
      title: '对象JSON',
      onOpen: function(){
          configForMethodCodeEditor1();
          MethodCodeEditor1.setValue(entityjson);
      },
    };
    var dlgButtonsIdx = [1];
    var dlgButtonsFunc =  [dlgClose];
    zUtil.dialogInit(IdDlgMethodEntityJson1,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen(IdDlgMethodEntityJson1);
  }
  //编辑器
  function configForMethodCodeEditor1(){
      if(MethodCodeEditor1 === null){
            MethodCodeEditor1 = CodeMirror.fromTextArea($(IdDlgMethodEntityJson1 +" #fieldJson")[0], {
                autoRefresh:true,
                lineNumbers: true,
                styleActiveLine: true,
                matchBrackets: true,
                lineWrapping: true,
                mode:"application/json",
           });
           MethodCodeEditor1.setSize('100%','100%');
      }
  }
  //通用可视化
  function configForMethodEntityViewEdit(nodeId){
      var node = $.extend(true,{},zUtil.tree(IdTreeMainMethod,"find",nodeId));
      var attr = node['attributes'];
      var methodx = zUtil.tableRows(IdTableConfigMethod);
      var entityData = zUtil.getVal(methodx,'entityData.'+attr['tagKey']);
      
      if(!entityData || entityData.length === 0
           || !entityData[0]['children'] || entityData[0]['children'].length === 0){
           zUtil.msg("未配置对象属性");
           return false;
      }
      zUtil.val(IdDlgMethodEntityViewEdit+ " #viewEditType1","1");
      zUtil.val(IdDlgMethodEntityViewEdit+ " #tagKey",attr['tagKey']);
      
      try{
          if(!configForMethodEntityViewEdit2(entityData)){
              return false;
          };
          //渲染一次
          initTemplateViewEdit(IdDlgMethodEntityViewEdit);
      }catch(b){
          console.log(b);
          zUtil.msg("模板实例化失败1");
          return false;
      }
      
      
      var dlgSave = function(){
          var cptId = $(IdDlgMethodEntityViewEdit + ' #uniqueId').val();
          if(cptId){
              var newnd = zUtil.valAll($(IdDlgMethodEntityViewEdit));
              zUtil.treegrid(IdTableTreeMethodEntity,"upd", {
                  id: cptId,
                  row: $.extend(true,{},newnd)
              });
              zUtil.treegrid(IdTableTreeMethodEntity,"rfh",cptId);
              zUtil.Toastr("success","已修改",null,{positionClass:"toast-top-center"});
          }
      };
      var dlgClose = function(){
        zUtil.dialogClose(IdDlgMethodEntityViewEdit);
      };
      var dlgOptions = {
        title: '简易可视化',
      };
      var dlgButtonsIdx = [0,1];
      var dlgButtonsFunc =  [dlgSave,dlgClose];
      zUtil.dialogInit(IdDlgMethodEntityViewEdit,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
      zUtil.dialogOpen(IdDlgMethodEntityViewEdit);
  }
  //模式改变
  function configForMethodEntityViewChange(checked){
      if(checked){
          var tagKey = zUtil.val(IdDlgMethodEntityViewEdit+ " #tagKey");
          if(tagKey){
              var methodx = zUtil.tableRows(IdTableConfigMethod);
              var entityData = zUtil.getVal(methodx,'entityData.'+tagKey);
              
              zUtil.formClear($(IdDlgMethodEntityViewEdit +" #view-opr"));
              try{
                  if(!configForMethodEntityViewEdit2(entityData)){
                      return false;
                  };
                  //渲染一次
                  initTemplateViewEdit(IdDlgMethodEntityViewEdit);
              }catch(b){
                  zUtil.msg("模板实例化失败");
                  return false;
              }
          }
      }
  }
function configForMethodEntityViewEdit2(entityData){
      var params = zUtil.valAll(IdDlgMethodEntityViewEdit);
      //请求后台
      var result = zUtil.ajaxPostSync(zGlobal["http"] + "/api/autocode/templateViewShow", {
          reqData:{
             entitys: entityData[0]['children'], viewEditType: params['viewEditType']
          }
      });
      var htmlStr = null;
      if(zCode["GLOBAL_SUCCESS"] == zUtil.getVal(result,zConst["busCode"])){
          htmlStr = result[zConst["resData"]]['htmlStr'];
      }
      if(!htmlStr || htmlStr === null){
          zUtil.msg('数据内容错误');
          return false;
      }
      $(IdDlgMethodEntityViewEdit+" #view-content").html(htmlStr);
      
      return true;
  }
  
  //对象配置-新增
  function tableTreeEntityAdd1(fid){
    var snode = zUtil.treegrid(IdTableTreeMethodEntity,"find",fid);
    
    var rowLeft = getTableLeft();
    if(rowLeft == null){
        return false;
    };
    
    var params = {};
    var dlgSave = function(){
      var srows =  $.extend(true,[],zUtil.treegrid(IdTableColumns,"getsta"));
      
      var getNode = function(crow){
      return {
              _uniqueId: zUtil.uuid(),
              fieldTitle: crow['columnTitle'],
              fieldCode: crow['columnCode'],
              fieldJavaCode: crow['columnJavaCode'],
              fieldJavaCode2: crow['columnJavaCode2']?crow['columnJavaCode2']:crow['columnJavaCode'],
              standardFlag: crow['standardFlag']?crow['standardFlag']:"0",
              javaFullType: crow['javaFullType'],
              javaType: crow['javaType'],
              javaVoType: crow['javaVoType'],
              jdbcType: crow['jdbcType'],
              mustFlag: crow['columnMandatory']=="0"?"1":"0",
              readonlyFlag: "0",
              pageOrder: "1",
              fieldType: crow['tableId']?"2":"1",
              pageShowFlag: "1",
              inputType: InputDefaultData?InputDefaultData['componentCode']:"",
              componentClazz: InputDefaultData?InputDefaultData['componentClazz']:"",
              componentType: InputDefaultData?InputDefaultData['componentType']:"",
              groupCode: "N",
              gridClonums: "6",
              inputNumber: "1",
              checkType:"2",
              fieldUseType:"1",
             };
      };
      if(srows!=null && srows.length>0){
         var datas =[];
         var cnodes = {};
         $.each(srows,function(i,crow){
             var node = getNode(crow);
             if(crow['tableId']){//选择的对象
                 node['children'] = $.extend(true,[],crow['children']);
                 datas.push(node);
             }else{//选择的字段
                 var tableCode = crow['tableCode'];
                 if(!cnodes[tableCode]){
                     cnodes[tableCode] = [];
                 }
                 cnodes[tableCode].push(node);
             }
         });
         if(datas.length>0){
             $.each(datas,function(i, d){
                 var childrenDt = cnodes[d['fieldCode']];
                 if(childrenDt){
                   d['children'] = childrenDt;
                 }else{//如果没有子节点则获取全部字段
                    var childn = d['children'];
                    var childdt = [];
                    $.each(childn,function(ci,crow){
                        childdt.push(getNode(crow));
                    });
                    d['children'] = childdt;
                 }
               });
         }else{
             $.each(cnodes,function(key,item){
                 $.extend(true, datas, item);
             });
         }
         zUtil.treegrid(IdTableTreeMethodEntity,'apd',{
             parent: snode['_uniqueId'],
             data: datas
         });
      }
      
      zUtil.dialogClose(IdDlgSelectTableCols);
    };
    var dlgClose = function(){
      zUtil.dialogClose(IdDlgSelectTableCols);
    };
    var dlgOptions = {
      title: '表字段选择',
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    zUtil.dialogInit(IdDlgSelectTableCols,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen(IdDlgSelectTableCols);
    
    var optionsEntity = {
            queryParams:{ projectId: rowLeft['projectId']},
            url : zGlobal["http"] + "/api/autocode/table/columnlist",
            idField: 'columnId',
            treeField:'columnTitle',
            sortName: 'orderNum',
            toolbar: IdTableColumnsTb,
            singleSelect: false,
            columns:[[
                {field: 'projectId', title: '所属项目', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"ZSELECT_PROJECT")}},
                {field: 'tableId', title: '表主键ID', align: 'center', width: 100, hidden: true},
                {field: 'columnId', title: '字段主键ID', align: 'center', width: 100, hidden: true},
                {field: 'tableTag', title: '标签', align: 'center', width: 150},
                {field: 'tableAlias', title: '表别名', align: 'center', width: 60},
                {field: 'columnCode', title: '字段CODE', align: 'center', width: 200},
                {field: 'columnJavaCode', title: '驼峰编码', align: 'center', width: 200},
                {field: 'columnPrimarykey', title: '是否主键', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'columnMandatory', title: '是否为空', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'standardFlag', title: '标准类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){return zUtil.dictConvertOfAutocode(value,"dict.booleanFlag")}},
                {field: 'javaFullType', title: 'JAVA类型', align: 'center', width: 150},
                {field: 'jdbcType', title: 'JDBC类型', align: 'center', width: 80},
                {field: 'orderNum', title: '排序', align: 'center', width: 50},
                {field: 'dataStatus', title: '状态', align: 'center', width: 50, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")}},
                {field: ' ', title: ' ', align: 'center', width: 30},
            ]],
            frozenColumns:[[
                {field:'', title:'', align:'center', width: 60, checkbox:true},
                {field: 'columnTitle', title: '标题', align: 'left',halign: 'center', width: 200},
            ]],
            loadFilter: function(data){
                var tmp = {rows:[],total:0};
                try{//解析不了就原样返回
                    var ndata = data[zConst["resData"]][zConst["data"]];
                    if(ndata){
                        for(var i=0; i< ndata.length; i++){
                            var  d = ndata[i];
                            d["columnId"] = d['tableCode'];
                            d["columnCode"] = d['tableCode'];
                            d["columnTitle"] = d['tableTitle'];
                            d["columnJavaCode"] = d['tableJavaCode'];
                            d["columnJavaCode2"] = d['tableJavaFullCode'];
                            d["tableTag"] = d['tableTag'];
                            d["state"] = "closed";
                            if(d["columnInfos"] && d["columnInfos"].length>0){
                               d["children"] = d["columnInfos"];
                               d["columnInfos"] = null;
                            }
                        }
                        tmp.rows = ndata;
                        tmp.total = data[zConst["resData"]][zConst["count"]];
                    }
                }catch(b){
                    return data;
                }
                return tmp;
             },
    };
    zUtil.treegridInit(IdTableColumns,optionsEntity);
    zUtil.treegrid(IdTableColumns,"usta");
  }
  function tableColumnsQuery(){
      var rowLeft = getTableLeft();
      if(rowLeft == null){
          return false;
      };
      var param = zUtil.valAll(IdTableColumnsTb);
      param['projectId'] = rowLeft['projectId'];
      zUtil.treegrid(IdTableColumns,"load", param);
  }
  function tableColumnsClearSelect(){
    zUtil.treegrid(IdTableColumns,"usta");
  }
  //对象配置-新增
  function tableTreeEntityAdd2(fid){
      var snode = zUtil.treegrid(IdTableTreeMethodEntity,"find",fid);
      var _uniqueId = zUtil.uuid();
      var rdno = getFieldRandomNo();
      zUtil.treegrid(IdTableTreeMethodEntity,'apd',{
          parent: snode['_uniqueId'],
          data: [{
              _uniqueId: _uniqueId,
              fieldTitle: "新字段"+ rdno,
              fieldCode: "",
              fieldJavaCode: "code" + rdno,
              fieldJavaCode2: "",
              mustFlag:"0",
              readonlyFlag: "0",
              standardFlag: "1",
              javaFullType: "java.lang.String",
              javaType: "String",
              javaVoType: "String",
              jdbcType: "VARCHAR",
              pageOrder: "1",
              fieldType: "1",
              pageShowFlag: "1",
              inputType: InputDefaultData?InputDefaultData['componentCode']:"",
              componentClazz: InputDefaultData?InputDefaultData['componentClazz']:"",
              componentType: InputDefaultData?InputDefaultData['componentType']:"",
              groupCode: "N",
              gridClonums: "6",
              inputNumber: "1",
              checkType:"2",
              fieldUseType:"1",
              }
            ]
      });
  }
  //对象配置-删除
  function tableTreeEntityDel(fid){
      var snode = zUtil.treegrid(IdTableTreeMethodEntity,"find",fid);
      if (snode){
          if(snode['fieldJavaCode'] === "ROOT"){
              var cdata = snode['children'];
              if(cdata){
                 cdata = $.extend(true,[],cdata);
                 $.each(cdata,function(key,item){
                     zUtil.treegrid(IdTableTreeMethodEntity,"rmv",item['_uniqueId']);
                 }); 
              }
          }else{
              zUtil.treegrid(IdTableTreeMethodEntity,"rmv",snode['_uniqueId']);
          }
      }
  }
  
  //对象配置-字段编辑
  function dlgEntityAttrOptions(fid){
      var snode = zUtil.treegrid(IdTableTreeMethodEntity,"find",fid);
      
      var leftRowData = getTableLeft();
      
      //获取扩展字段并实例化
      $(IdMethodEntityAttrEx).empty();
      zUtil.formClear(IdMethodEntityAttr);
      
      
      var dlgSave = function(){
          var params = zUtil.valAll(IdMethodEntityAttr);
          var params2 = zUtil.valAll(IdMethodEntityAttrOther);
          
          var newnd = {};
          var batchFlagVal = params2['batchFlag'];
          var batchFlagY = ("2" === batchFlagVal || "3" === batchFlagVal);
          
          var selectFields = {};
          
          if(batchFlagY){
              var cknums = 0;
              $(IdMethodEntityAttr + " .js-check").each(function(i,e){
                  if(e.id){
                      var fname = (e.id).substring(3);
                      var ckStatus = zUtil.inputInit(e,"check-options").checked;
                      if(ckStatus){
                         selectFields[fname] = ckStatus;
                         if(fname === "inputType"){
                             selectFields['componentType'] = ckStatus;
                         }
                         if(fname === "inputOptions1"){
                             selectFields['inputOptions2'] = ckStatus;
                             selectFields['inputOptions3'] = ckStatus;
                         }
                         cknums++;
                      }
                  }
              });
              if(cknums === 0){
                  zUtil.msg("批量更新需选择左侧字段值");
                  return false;
              }
          }
          
          $.each(params,function(key,value){
              if(value && value != null){
                  var ckStatus = selectFields[key];
                  if((ckStatus && batchFlagY) || !batchFlagY){
                      if("NAN" === value){
                          newnd[key] = null;
                      }else{
                          if('array' === $.type(value)){
                             newnd[key] = value.toString();
                          }else{
                            newnd[key] = value;
                          }
                      }
                  }
              }
          });
          
          var updIds = [];
          
          if(batchFlagY){
              var cknodes = zUtil.tree(IdTreeMethodEntityAttr,'getck');
              if(cknodes.length === 0){
                  zUtil.msg("批量更新需选择右侧字段");
                  return false;
              }
              $.each(cknodes,function(i, item){
                  if(fid !== item.id){
                      updIds.push(item.id);
                  }
              });
              if("3" === batchFlagVal){
                  updIds.push(fid);
              }
          }else{
              updIds.push(fid);
          }
          $.each(updIds,function(i, val){
              zUtil.treegrid(IdTableTreeMethodEntity,"upd",{
                  id: val,
                  row: $.extend(true,{},newnd)
              });
          });
          var inputDict = newnd['inputDict'];
          if(inputDict && inputDict!=null){
              configForMethodEntityChangeDict(inputDict);
          }
          
          zUtil.Toastr("success","已修改",null,{positionClass:"toast-top-center"});
        };
        var dlgClose = function(){
          zUtil.dialogClose(IdDlgMethodEntityEdit);
        };
        var dlgOptions = {
          title: '字段编辑',
          collapsible: true,
          modal: false,
          onBeforeOpen: function(){
              
          }
        };
        var dlgButtonsIdx = [0,1];
        var dlgButtonsFunc =  [dlgSave,dlgClose];
        zUtil.dialogInit(IdDlgMethodEntityEdit,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
        zUtil.dialogOpen(IdDlgMethodEntityEdit);

      //初始化
      var attrExtendFieldJSON = zUtil.parse(zUtil.val(IdDlgRightOpen +" #attrExtendField"));
      if(attrExtendFieldJSON == null){
        attrExtendFieldJSON = [];
      }
      if(attrExtendFieldJSON != null){
          for(var i=0;i<attrExtendFieldJSON.length;i++){
             entityAttrEditInputEl(attrExtendFieldJSON[i])
          }
      }
      
      zUtil.inputInit(IdMethodEntityAttr + ' #inputType','cgrid',{
            readonly: JsonReadonly, 
            url: zGlobal["http"] + "/api/autocode/webComponent/list?page=1&limit=200",
            queryParams: {projectId: leftRowData['projectId'],"sort":"orderNum","order":"desc"},
            panelWidth:600,
            panelHeight:300,
            columns: [[
                {field: 'componentId', title: '组件主键ID', align: 'center', width: 100, hidden:true},
                {field: 'componentCode', title: '组件编码', align: 'center', width: 150},
                {field: 'componentTitle', title: '标题', align: 'center', width: 120},
                {field: 'componentClazz', title: '样式', align: 'center', width: 100},
                {field: 'componentType', title: '类型', align: 'center', width: 100, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"component.componentType")}},
                {field: 'dataStatus', title: '状态', align: 'center', width: 60, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")} },
                {field: ' ', title: ' ', align: 'center', width: 30},
            ]],
            onSelect: function(index, row){
                if(row){
                   zUtil.val(IdMethodEntityAttr + ' #inputType',row['componentCode']);
                   zUtil.val(IdMethodEntityAttr + ' #inputClass',row['componentClazz']);
                   zUtil.val(IdMethodEntityAttr + ' #componentType',row['componentType']);
                }
            },
      });
      //
      var tableinfos =zUtil.treegrid(IdTableConfigTbl,'getdt');
      var ttables = [];
      $.each(tableinfos,function(i,tblx){
          var childrens = tblx.children;
          if(childrens && childrens.length>0){
              $.each(childrens,function(i,childx){
                   var sqldata = {
                          "tableSqlTitle": tblx['tableTitle']+" . "+childx['tableTitle'],
                          "tableSqlCode": tblx['tableJavaCode']+" . "+childx['tableCode'],
                          "useTableCode": tblx['tableJavaCode'],
                          "useTableSqlCode": childx['tableCode'],
                   };
                   ttables.push(sqldata);
              });
          }
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #useTableCode'+','+IdMethodEntityAttr + ' #useTableSqlCode','cgrid',{
          readonly: JsonReadonly, 
          data: ttables,
          panelWidth:600,
          panelHeight:300,
          columns: [[
              {field: 'tableSqlTitle', title: '标题', align: 'left',halign: 'center', width: 250, },
              {field: 'tableSqlCode', title: '编码', align: 'left',halign: 'center', width: 250, },
              {field: 'useTableCode', title: '表编码', align: 'center', hidden:true },
              {field: 'useTableSqlCode', title: 'SQL编码', align: 'center', hidden:true },
              {field: ' ', title: ' ', align: 'center', width: 50},
          ]],
//          onLoadSuccess: function(data){},
          onSelect: function(index, row){
              if(row){
                  zUtil.val(IdMethodEntityAttr + ' #useTableCode',row['useTableCode']);
                  zUtil.val(IdMethodEntityAttr + ' #useTableSqlCode',row['useTableSqlCode']);
              }
          },
      });
      
      
      zUtil.inputInit(IdMethodEntityAttr + ' #mustFlag','select',{
         data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #readonlyFlag','select',{
          data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #pageShowFlag','select',{
          data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)
       });
      zUtil.inputInit(IdMethodEntityAttr + ' #fieldType','select',{
          data: zUtil.dataFormat(zDictAutocode['cfg.fieldType'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #standardFlag','select',{
          data: zUtil.dataFormat(zDictAutocode['dict.booleanFlag'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #checkType','select',{
          data: zUtil.dataFormat(zDictAutocode['validation.fieldType'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #fieldUseType','select',{
          data: zUtil.dataFormat(zDictAutocode['cfg.fieldUseType'],0)
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #conditionSymbol','select',{
          data: zUtil.dataFormat(zDictAutocode['cfg.conditionSymbol'],0)
      });
      
      zUtil.inputInit(IdMethodEntityAttr + ' #selectTemplate','select',{valueField:'id',textField:'text',multiple:true,groupField: "group",panelHeight:200,data:MethodChildEntityTemplates,
          groupFormatter: function(group){
              return zUtil.dictConvertOfAutocode(group,"template.outputType");
          } });
      zUtil.inputInit(IdMethodEntityAttr + ' #checkBackground','input',{
          readonly: JsonReadonly, 
          icons:[{
              iconCls:'icon-add',
              text:'快捷选择',
              handler: function(e){
                  zUtil.dialogInit('#dlg-select-checkBackground'
                          , {
                              title: "前端和后台校验规则(覆盖)",
                              width: 650,
                              height: 450,
                              draggable: true,
                              onOpen:function(){
                                  dlgSelectCheckRules(leftRowData,"1");
                              }
                            }
                          , [0,1]
                          , [function(){
                                var row = zUtil.tableRows('#table-checkBackground');
                                zUtil.val(IdMethodEntityAttr + ' #maxVal',row['maxVal']);
                                zUtil.val(IdMethodEntityAttr + ' #minVal',row['minVal']);
                                zUtil.val(IdMethodEntityAttr + ' #checkPage',row['checkPage']);
                                zUtil.val(IdMethodEntityAttr + ' #checkType',row['fieldType']);
                                zUtil.val(IdMethodEntityAttr + ' #checkBackground',row['checkBackground']);
                                zUtil.dialogClose('#dlg-select-checkBackground');
                            },function(){
                                zUtil.dialogClose('#dlg-select-checkBackground');
                            }]
                 );
                 zUtil.dialogOpen('#dlg-select-checkBackground');
              }
          }],
          buttonText:'追加选择',
          onClickButton:function(){
              zUtil.dialogInit('#dlg-select-checkBackground'
                      , {
                          title: "后台校验规则(追加)",
                          width: 600,
                          height: 450,
                          draggable: true,
                          onOpen:function(){
                              dlgSelectCheckRules(leftRowData,"2");
                          }
                        }
                      , [0,1]
                      , [function(){
                            var row = zUtil.tableRows('#table-checkBackground');
                            if(row){
                                var hasVal = zUtil.val(IdMethodEntityAttr + ' #checkBackground')
                                zUtil.val(IdMethodEntityAttr + ' #checkBackground', hasVal?hasVal+" "+row['checkBackground']:row['checkBackground']);
                            }
                            zUtil.dialogClose('#dlg-select-checkBackground');
                        },function(){
                            zUtil.dialogClose('#dlg-select-checkBackground');
                        }]
             );
             zUtil.dialogOpen('#dlg-select-checkBackground');
          },
      });
      zUtil.inputInit(IdMethodEntityAttr + ' #checkPage','input',{
          readonly: JsonReadonly, 
          buttonText:'追加选择',
          onClickButton:function(){
              zUtil.dialogInit('#dlg-select-checkBackground'
                      , {
                          title: "前端校验规则(追加)",
                          width: 550,
                          height: 450,
                          draggable: true,
                          onOpen:function(){
                              dlgSelectCheckRules(leftRowData,"3");
                          }
                        }
                      , [0,1]
                      , [function(){
                            var row = zUtil.tableRows('#table-checkBackground');
                            if(row){
                                var hasVal = zUtil.val(IdMethodEntityAttr + ' #checkPage')
                                zUtil.val(IdMethodEntityAttr + ' #checkPage', hasVal?hasVal+","+row['checkPage']:row['checkPage']);
                            }
                            zUtil.dialogClose('#dlg-select-checkBackground');
                        },function(){
                            zUtil.dialogClose('#dlg-select-checkBackground');
                        }]
             );
             zUtil.dialogOpen('#dlg-select-checkBackground');
          }
      });
      
      var datas = $.extend(true,{},zUtil.treegrid(IdTableTreeMethodEntity,"getrt"));
      var getEntityAttrData = function(data,rootflag){
          var troenode = {};
          troenode["id"] =  data['_uniqueId'];
          troenode["text"] =  " 【"+ data['fieldTitle'] + "】-- "+ data['fieldJavaCode'];
          troenode["rootflag"] =  rootflag;
          if(data['children'] && data['children'].length > 0){
             if("N" === rootflag){
                 troenode["state"] =  "closed"; 
             }
             var childnode = [];
             $.each(data['children'],function(i,item){
                 childnode.push(getEntityAttrData(item,"N"));
             }); 
             troenode["children"] = childnode;
          }
          return troenode;
      };
      zUtil.treeInit(IdTreeMethodEntityAttr,{
          data: [getEntityAttrData(datas,"Y")],
          cascadeCheck: false,
          checkbox: true,
          dnd:true,
          onBeforeCheck: function(node, checked){
              if("Y" === node["rootflag"]){
                  var selectChildFunc = function(node){
                      var cnodes = zUtil.tree(IdTreeMethodEntityAttr,'getcld',node.target);
                      if(cnodes){
                          $.each(node.children,function(i,itemx){
                               if(!itemx.checked){
                                  zUtil.tree(IdTreeMethodEntityAttr,'ck',itemx.target); 
                               }else{
                                  zUtil.tree(IdTreeMethodEntityAttr,'unck',itemx.target); 
                               }
                               if(itemx.children){
                                   selectChildFunc(itemx);
                               }
                          });
                      }
                  };
                  selectChildFunc(node);
                  return false;
              }
          },
          onSelect: function(node){
             if(!node.checked){
                zUtil.tree(IdTreeMethodEntityAttr,'ck',node.target); 
             }else{
                zUtil.tree(IdTreeMethodEntityAttr,'unck',node.target); 
             }
          },
          formatter: function(node){
              if(fid === node.id){
                  return '<span style="color:red;">' + node.text + '</span>';
              }else{
                  return node.text;
              }
          },
          onBeforeDrop:function(target, source, point){
              //不能变更节点层级
              if(point !== 'bottom' && point !== 'top'){
                  zUtil.Toastr("warn","对象层级变更",null); 
              }
          }
      });
      
      zUtil.valAll(IdMethodEntityAttr, snode, {clearForm: false});
      zUtil.valAll(IdMethodEntityAttrOther, {'batchFlag':"1"}, {clearForm: false});
      
      
  }
  function entityAttrEditClear(oprType){
      if("1" === oprType){
         var cknodes = zUtil.tree(IdTreeMethodEntityAttr,'getck');
         $.each(cknodes,function(i, item){
             zUtil.tree(IdTreeMethodEntityAttr,'unck',item.target);
         });
      }else if("2" === oprType){
          $(IdMethodEntityAttr + " .js-check").each(function(i,e){
              if(e.id){
                  var fname = (e.id).substring(3);
                  var ckStatus = zUtil.inputInit(e,"check-options").checked;
                  if(ckStatus){
                      zUtil.inputInit(e,"check-uncheck");
                  }
              }
          });
       }
  }
  function entityAttrEditSort(){
      var okfunc = function(){
          var allnodes = zUtil.tree(IdTreeMethodEntityAttr,'getrt');
          var datas = zUtil.treegrid(IdTableTreeMethodEntity,"getrt");
          
          var nodedt = {};
          var getChildData = function(data){
              if(!data){
                return [];
              }
              $.each(data,function(i,item){
                nodedt[item['_uniqueId']] = item;
                //不要
                delete item['_parentId'];
                delete item['checkState'];
                delete item['checked'];
                delete item['state'];
                if(item['children']){
                     if(item['children'].length>0){
                         item['children'] = getChildData(item['children']);
                     }
                     delete item['children'];
                }
              });
              return data;
          }
          getChildData($.extend(true,[],datas['children']));
          
          var sortdt = [];
          var getChildData2 = function(data,sortdt){
              $.each(data,function(i,item){
                var _uniqueId = item['id'];
                var node = $.extend(true,{},nodedt[_uniqueId]);
                if('array' === $.type(sortdt)){
                    sortdt.push(node);
                }else{
                    sortdt['children'].push(node);
                }
                if(item['children']){
                     if(item['children'].length>0){
                       node['children'] = [];
                       getChildData2(item['children'], node['children']);
                    }
                }
              });
          }
          getChildData2($.extend(true,[],allnodes['children']),sortdt);
          
          datas['children'] = sortdt;
          zUtil.treegrid(IdTableTreeMethodEntity,'ldt', [datas]);
      }
      zUtil.msgConfirm("是否保存最新树结构，如没有进行拖拽则无需同步?",okfunc);
  }
  
  
  function entityAttrEditInputEl(options,elType){
    var handleElHtml = function(inputhtml, ftitle,zcode){
        var elObj = $('<div class="col-sm-6"><label class="form-lable" title="'+zcode+'">'+ ftitle 
        +'<div style="position: absolute;top: 5px;right: 0;"><input class="easyui-checkbox js-check" id="CK_'+zcode+'"/>'
        +'</div></label><div class="input-block">'+ inputhtml + '</div></div>');
        $(IdMethodEntityAttrEx).append(elObj);
    }
    var opts = $.extend(true, {
        text: "text",
        value: "value",
        method: "get",
    }, options.mores);
    
    var zcode = options.code;
    var ztitle = options.title;
    var ztype = options.type;
    var zloadtype = options.loadtype;
    var zdata = options.mores.data;
    var zlabel = opts.text;
    var zvalue = opts.value;
    var zmethod = opts.method;
    var zinputobj = null;
    
    if(ztype == "1"){
        var datas = getSwitchData();
        var elObj = '<span class="textbox textbox2 easyui-fluid"><div class="input-g">'
                  +'<input id="'+zcode+'1" name="'+zcode+'" class="easyui-radiobutton" /> 否'
                   +'    <input id="'+zcode+'2" name="'+zcode+'" class="easyui-radiobutton" /> 是</div></span>';
        handleElHtml(elObj,ztitle,zcode);
        zUtil.inputInit(IdMethodEntityAttrEx + " #"+zcode+"1", 'radio',{
            value:"0", checked: true
        });
        zUtil.inputInit(IdMethodEntityAttrEx + " #"+zcode+"2", 'radio',{
            value:"1"
        });
        zUtil.inputInit(IdMethodEntityAttrEx + " #CK_"+zcode, 'check');
    }else if(ztype == "2"){
        var elObj = '<input id="'+zcode+'" name="'+zcode+'" class="easyui-textbox" style="width:100%;" />';
        handleElHtml(elObj,ztitle,zcode);
        zUtil.inputInit(IdMethodEntityAttrEx + " #"+zcode, 'input');
        zUtil.inputInit(IdMethodEntityAttrEx + " #CK_"+zcode, 'check');
    }else if(ztype == "3" || ztype == "4"){
       var datas = getSelectData(zloadtype,zdata,zmethod,opts);
       var elObj = '<select id="'+zcode+'" name="'+zcode+'" class="easyui-combobox" style="width:100%;" ></select>';
       handleElHtml(elObj,ztitle,zcode);
       var multipleFlag = ztype == "4"? true : false;
       zUtil.inputInit(IdMethodEntityAttrEx + " #"+zcode, 'select',{
           valueField: zvalue, textField: zlabel, panelHeight: 200, 
           multiple: multipleFlag,
           value: datas[0][zvalue],
           data: datas,
       });
       zUtil.inputInit(IdMethodEntityAttrEx + " #CK_"+zcode, 'check');
    }
  }
  
  //对象配置-新增
  function tableTreeEntityAdd3(fid){
    var snode = zUtil.treegrid(IdTableTreeMethodEntity,"find",fid);
    
    zUtil.formClear(IdDlgMethodEntityJson2);
    
    
    var dlgSave = function(){
      var srows =  {};
      
      var jsonVal = zUtil.parse(MethodCodeEditor2.getValue());
      
      if(jsonVal === null || 'array' !== $.type(jsonVal)){
          zUtil.msg("JSON格式错误");
          return;
      }
      
      var dnode = {
              fieldCode: "",
              fieldJavaCode2: "",
              mustFlag:"0",
              standardFlag: "1",
              javaFullType: "java.lang.String",
              javaType: "String",
              javaVoType: "String",
              jdbcType: "VARCHAR",
              pageOrder: "1",
              fieldType: "1",
              pageShowFlag: "1",
              inputType: InputDefaultData?InputDefaultData['componentCode']:"",
              componentClazz: InputDefaultData?InputDefaultData['componentClazz']:"",
              componentType: InputDefaultData?InputDefaultData['componentType']:"",
              groupCode: "N",
              gridClonums: "6",
              inputNumber: "1",
              checkType:"2",
              fieldUseType:"1",
      };
      
      
      var getChildData = function(data){
          if(!data){
            return [];
          }
          $.each(data,function(i,item){
             if(item['fieldTitle'] && item['fieldJavaCode']){
                 item['_uniqueId'] = zUtil.uuid();
                 
                 $.extend(dnode,item);
                 
                 if(item['children']){
                     if(item['children'].length>0){
                         item['children'] = getChildData(item['children']);
                     }else{
                         delete item['children'];
                     }
                 }
             }else{
                 zUtil.msg("缺少fieldTitle、fieldJavaCode");
                 return false;
             }
          });
          return data;
      }
      
      zUtil.treegrid(IdTableTreeMethodEntity,'apd',{
          parent: snode['_uniqueId'],
          data: getChildData(jsonVal)
      });
      
      zUtil.dialogClose(IdDlgMethodEntityJson2);
    };
    var dlgClose = function(){
      zUtil.dialogClose(IdDlgMethodEntityJson2);
    };
    var dlgOptions = {
      title: '新增字段JSON',
      onOpen: function(){
          configForMethodCodeEditor2();
          MethodCodeEditor2.setValue("");
      },
    };
    var dlgButtonsIdx = [0,1];
    var dlgButtonsFunc =  [dlgSave,dlgClose];
    zUtil.dialogInit(IdDlgMethodEntityJson2,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
    zUtil.dialogOpen(IdDlgMethodEntityJson2);
  }
  //编辑器
  function configForMethodCodeEditor2(){
      if(MethodCodeEditor2 === null){
            MethodCodeEditor2 = CodeMirror.fromTextArea($(IdDlgMethodEntityJson2 +" #fieldJson")[0], {
                autoRefresh:true,
                lineNumbers: true,
                styleActiveLine: true,
                matchBrackets: true,
                lineWrapping: true,
                mode:"application/json",
           });
           MethodCodeEditor2.setSize('100%','100%');
      }
  }
  
  function dlgEntityInputOpts(){
      if(JeditorMethodEntityInputOpts !== null){
          zUtil.jeditorClear(JeditorMethodEntityInputOpts);
      }
      
      var currInputTypeData= InputDataMap[zUtil.val(IdMethodEntityAttr + ' #inputType')];
      var componentOption1JSON = null;
      var componentTemplateJSON = null;
      if(currInputTypeData){
          componentOption1JSON = zUtil.parse(currInputTypeData['componentOption1']);
          componentTemplateJSON =  zUtil.parse(currInputTypeData['componentTemplate']);
      }
      
      var inputOptions1JSON = zUtil.parse(zUtil.val(IdMethodEntityAttr + ' #inputOptions1'));
      var inputOptions3JSON = zUtil.parse(zUtil.val(IdMethodEntityAttr + ' #inputOptions3'));
      
      if(!componentOption1JSON && !inputOptions1JSON){
          zUtil.msg("没有设置组件属性");
          return false;
      }
      
      var hascode ={};
      var hasInputOptionsMap = {};
      if(inputOptions1JSON != null){
          if(componentOption1JSON != null){
              $.each(inputOptions3JSON,function(i,item){
                 hasInputOptionsMap[item['code']] = item;
              });
              
              $.each(componentOption1JSON,function(i,item){
                     var code = item['code'];
                     var val = inputOptions1JSON[code];
                     if(val){
                         item["value"] = inputOptions1JSON[code];
                         if(hasInputOptionsMap[code] && hasInputOptionsMap[code] !== null){
                             item["type"] = hasInputOptionsMap[code]["type"];
                         }
                     }else{
                         item["value"] = null;
                     }
                     hascode[code] = "Y";
              });
          }else{
            componentOption1JSON =[];
          }
          
          $.each(inputOptions1JSON, function(key,val){
              if(!hascode[key]){
                componentOption1JSON.push({
                  "code": key,
                  "title": hasInputOptionsMap[key]?hasInputOptionsMap[key]["title"]:key,
                  "must": false,
                  "value": val,
                  "type": hasInputOptionsMap[key]?hasInputOptionsMap[key]["type"]:"string"
                });
            }
          });
      }
      
      if(componentTemplateJSON!=null){
      
      }
      
      var jsonOpts = inputAttrDefine();
      var configVal = componentOption1JSON;
      JeditorMethodEntityInputOpts = zUtil.jeditor(IdDlgMethodEntityInputOpts + " #jsonedit_JSON",jsonOpts,configVal);
      
      
      var dlgSave = function(){
        const jsondata = zUtil.jeditorData(JeditorMethodEntityInputOpts);
        var inputOptions1JSON = {};
        var inputOptions2JSON = "";
        if(jsondata){
            $.each(jsondata,function(i,item){
                if(item['value'] != null && item['value'] != ""){
                    var code = item['code'];
                    var value = item['value'];
                    var type = item['type'];
                    inputOptions1JSON[code] = value;
                    
                    if("string" !== type){
                        inputOptions2JSON += '"'+code+'\": '+ value +',';
                    }else{
                        inputOptions2JSON += '"'+code+'": "'+ value +'",';
                    }
                }
            });
            inputOptions2JSON = "{" + inputOptions2JSON + "}";
            
            zUtil.val(IdMethodEntityAttr + ' #inputOptions1', zUtil.strify(inputOptions1JSON));
            zUtil.val(IdMethodEntityAttr + ' #inputOptions2', inputOptions2JSON);
            zUtil.val(IdMethodEntityAttr + ' #inputOptions3', zUtil.strify(jsondata));
        }
        
        zUtil.dialogClose(IdDlgMethodEntityInputOpts);
      };
      var dlgClose = function(){
        zUtil.dialogClose(IdDlgMethodEntityInputOpts);
      };
      var dlgOptions = {
        title: '组件属性编辑',
        collapsible: true,
        modal: false,
      };
      var dlgButtonsIdx = [0,1];
      var dlgButtonsFunc =  [dlgSave,dlgClose];
      zUtil.dialogInit(IdDlgMethodEntityInputOpts,dlgOptions,dlgButtonsIdx,dlgButtonsFunc);
      zUtil.dialogOpen(IdDlgMethodEntityInputOpts);
  }
  function inputAttrDefine(){
      const attrExJson = {
              "type": "object",
              "title": "属性",
              "required": ["code","title","desc","must","type","value"],
              "format": "grid",
              "properties": {
                  "code":{
                      "type": "string",
                      "title": "编码",
                      "readOnly": true,
                      "options": {
                          "input_width": '120px',
                      }
                   },
                  "title":{
                      "type": "string",
                      "title": "名称",
                      "readOnly": true,
                      "options": {
                          "input_width": '150px',
                      }
                  },
                  "must":{
                      "type": "boolean",
                      "title": "必填",
                      "default":false,
                      "readOnly": true,
                      "options": {
                          "input_width": '90px',
                      }
                  },
                  "desc":{
                      "type": "string",
                      "title": "描述",
                      "readOnly": true,
                      "format": "textarea",
                      "options": {
                          "input_width": '150px',
                      }
                  },
                  "type":{
                      "type": "string",
                      "title": "类型",
                      "enum": ["string", "number", "array","boolean", "function"],
                      "default":"string",
                      "readOnly": JsonReadonly,
                      "options": {
                          "enum_titles": ["字符", "数字", "数组","布尔","方法/变量"],
                          "input_width": '100px',
                      }
                  },
                  "value":{
                      "type": "string",
                      "title": "值",
                      "readOnly": JsonReadonly,
                      "format": "textarea",
                      "options": {
                          "input_width": '300px',
                      }
                  },
              }
      };
        var jsonOpts = {
                "schema": {
                    "type": "array",
                    "title": "组件配置",
                    "uniqueItems": true,
                    "format": "table",
                    "options": {
                        "disable_collapse": true,
                        "disable_edit_json": true,
                        "disable_array_add": true,
                        "disable_array_delete": true,
                        "disable_array_reorder": true,
                    },
                    "items": attrExJson
                    
                }
                ,
                "theme": "bootstrap3",
                "disable_array_add": JsonReadonly,
                "disable_array_delete": JsonReadonly,
                "disable_array_reorder": JsonReadonly, 
        };
        return jsonOpts;
  }
  
  function getOptionAttrType(value) {
      if(!value){
         return "string";
      }
      var isNum = /^\d+$/;
      var isArr = /(\[.*\])+/;
      var isBln = /^(true){1}$|^(false){1}$/;
      var isFunc = /^(\s*function)/;
      if(isArr.test(value)){
          return "array";
      }else if(isBln.test(value)){
          return "boolean";
      }else if(isNum.test(value)){
          return "number";
      }else if(isFunc.test(value)){
          return "function";
      }else{
          return "string";
      }
  }
  
  function getFieldRandomNo(ln) {
      var arrayChars1 = ["A","B","C","D","E","F","G","H","J","K"];
      var arrayChars2 = ["1","2","3","4","5","6","7","8","9"];
      var rarr1 = [];
      var rarr2 = [];
      ln = ln?ln:2;
      for(var i=0;i<ln;i++){
        var randomItem1 = arrayChars1[Math.floor(Math.random() * arrayChars1.length)];
        var randomItem2 = arrayChars2[Math.floor(Math.random() * arrayChars2.length)];
        rarr1.push(randomItem1);
        rarr2.push(randomItem2);
      }
      return rarr1.join("") + rarr2.join("");
  }
  
  function dlgSelectCheckRules(leftRowData,type){
        zUtil.tableInit2('#table-checkBackground',{
              idField: 'validationId',
              sortName: 'orderNum',
              sortOrder: 'desc',
              toolbar:'#table-checkBackground-toolbar',
              url: zGlobal["http"] + "/api/autocode/validation/list?page=1&limit=500",
              queryParams: {projectId: leftRowData['projectId'], moduleId: leftRowData['moduleId'],sort:"orderNum",order:"desc"},
              columns: [[
                      {field: 'validationId', title: '校验规则主键ID', align: 'center', width: 100, hidden: true},
                      {field: 'fieldType', title: '校验类型', align: 'center', width: 80, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"validation.fieldType")}},
                      {field: 'checkBackground', title: '校验规则(后台)', align: 'center', width: (type==="2"?220:150),hidden:!(type==="1"||type==="2")},
                      {field: 'checkPage', title: '校验规则(前端)', align: 'center', width: (type==="3"?220:150),hidden:!(type==="1"||type==="3")},
                      {field: 'maxVal', title: '最大值', align: 'center', width: 70,hidden:!(type==="1")},
                      {field: 'minVal', title: '最小值', align: 'center', width: 70,hidden:!(type==="1")},
                      {field: 'dataStatus', title: '状态', align: 'center', width: 50, formatter: function(value,rowData,rowIndex){ return zUtil.dictConvertOfAutocode(value,"dict.dataStatus")}},
                      {field: ' ', title: ' ', align: 'center', width: 30},
              ]],
              frozenColumns:[[
                  {field: 'validationTitle', title: '校验标题', align: 'center', width: 140},
              ]],
        });
}